简体   繁体   中英

How to use cross-origin cookies for server-side rendering?

I have a server-side rendered web app running on localhost:3000 and the API on localhost:3010 . How do I set the same cookie on both domains after a request to the API?

When I log in, I'm sending a POST request to localhost:3010 and it's setting a cookie like this:

const token = jwt.sign({ id, email }, secret, { expiresIn });
res.cookie('authorization', token, { signed: true, httpOnly: true, maxAge: 10000000 });

My problem is I can't figure out how to set that cookie on the app at localhost:3000 . I was just using localStorage before, but it doesn't work for server-side rendering when I have my API and app on different domains.

Here's how my server-side rendering middleware on localhost:3000 looks like, trying to access said cookie:

import Cookies from 'universal-cookie';

export function serverSideRendering(req, res, next) {
  const cookies = new Cookies(req.headers.cookie);
  const token = cookies.get('authorization');
  // ...
}

Try to change property name "authorization" to "JWT-token";

res.cookie('JWT-token', token, { signed: true, httpOnly: true, maxAge: 10000000 });

or you can try native node js method;

res.writeHead(200, {
  'Set-Cookie': 'authorization='+token,
});

And my advice, don't use cookie, use headers fields. It's helps you in future to increase your app to ios and android apps.

And you can keep your token inside store of your app, it's more secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM