0

I'm working on MERN stack application. There are two types of endpoints in my applications. One for API and another for static routes (using handlebars in NodeJS). I have used the basic JWT token to secure the API endpoints which would be accessible by React App. But JWT is not useful for static routes.

So How can I use single authentication for both types of routes?
Static routes are preview URL which is generated by admin panel. Only authenticated users can access them. HubSpot has the same strategy for the pages, Preview URL of pages can only be accessible by authenticated users.

Is there any other way to authenticate both endpoint types?

1 Answer 1

0

We can try the following way to achieve this requirement. Host a NodeJS on the primary domain where APIs and static routes will run. And Host a react app on a subdomain where the admin panel run. so the domains would be as follows:
React path would be app.website.com
Node path would be website.com

A user can login via API in react app and store the token in cookies with the primary domain. Now we can verify JWT in static routes by retrieving that token from the cookie.

Store a token in cookie:

document.cookie = `token=${TOKEN};expires;;domain=${PRIMARY_DOMAIN};path=/`;

Middleware to check the authentication:

const { token } = req.cookies
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
    if (err) {
        return res.status(401).send("Unauthorized!");
    }
    req.user = decoded;
});
next()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.