Q . ReactJS how to use cookie while rendering from server side?

Brad Johnson. asked, Mar 13 ' 2019

I am using reactJS for my project and creating cookie using react-cookie in client side,
Actually the problem is when its rendering from the server side it is getting undefined.
How to get the cookie in server side rendering as well.

creating cookie in client.

import cookie from 'react-cookies'

cookie.save('user', userData);

and retrieve

var userData = cookie.load('user');

I see that the cookie is saved into browser and I can use it in client side after the component is loaded but I need it in server side for pre-rendering operations. So the question is how to achive that? Or, if cookie is not the right approach, what is the best way to do it?

  • Server Side Rendering

1 Answers

Are you using the cookie-parser middleware? From the react-cookie docs:

You can also plug it directly with a Node.js request by adding just before the renderToString:

import cookie from 'react-cookies'

cookie.plugToRequest(req, res);

(require the cookieParser middleware)

Express won't parse requests to get the cookie out unless you have some cookie parsing middleware installed and enabled in your Express app.

Leave a Ansewer