Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS using cookie while rendering on server side

I am working on a web application and I used this starter kit as base of my project. The problem is that the cookie is not available in server side so I cannot use it for rendering a component in server.

I use react-cookie to save the account data after login

cookie.save('account', accountData)

and retrieve

var account = cookie.load('account')

it when I need it. 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?

like image 283
eluleci Avatar asked Dec 30 '15 08:12

eluleci


People also ask

Can you react using server-side rendering?

Yes! This is where server-side rendering for React comes in. In this article, I want to introduce you to server-side rending (SSR) with React, reasons to use it, and some popular frameworks for rendering React on the server side.

Are cookies created at server-side?

Cookies always belong to the client. There is no such thing as server side cookie.

Should I use server-side rendering react?

Server-side rendering is an excellent option for rendering web pages to increase the initial page load speed, improve SEO and provide a better user experience. The best part about web technology is the availability of platforms and frameworks that make complex concepts easier to implement.

What is cookie in server-side?

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with later requests.


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:

reactCookie.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.

like image 150
Michelle Tilley Avatar answered Sep 28 '22 18:09

Michelle Tilley