React / Redux Server Initial Rendering Status

I have a React / Redux application that monitors user authentication status in local storage. The application is also configured to use server-side rendering. When starting the initial state of the application, problems arise. My server creates a new repository and emits the SET_INITIAL_STATE action. This initial client-side action reads localStorage and passes the authenticated information to my reducers. However, the server does not know this registered state, since I am using a stand-alone JWT located in local storage for authentication.

Since at this stage the server and client are not synchronized, I get this error:

The reaction attempted to reuse the markup in the container, but the checksum was invalid. This usually means that you are using server rendering, and the markup generated on the server was not what the client expected. React introduces new markup to compensate for what works, but you have lost many of the benefits of server rendering. Instead, find out why the markup you create is different on the client or server:

This makes sense because the server is trying to display an unverified state.

What is an acceptable standard or practice for setting this initial state, which depends solely on what the client has access to?

+5
source share
2 answers

I found that OP is right that cookie storage is the best option. If you use reaction, abbreviation and expression for a universal application, then the option that worked for me was https://github.com/eXon/react-cookie .

Essentially:

In the server code you can use:

import cookie from 'react-cookie'; function handleRender(req, res) { cookie.setRawCookie(req.headers.cookie); // Create new Redux store instance const store = createStore(rootReducer, { username: cookie.load('username') || '', accessLevel: cookie.load('accessLevel') || userRoles.public, }); //other react/redux/express related code } 

In your reaction applications inside the components, you can simply save cookies directly:

  import cookie from 'react-cookie'; //first parameter is anything you want, second is the data you want to save cookie.save( 'username', username ); cookie.save('accessLevel', accessLevel); 

Further, if you want to save the object, like me, you can go to JSON.stringify(your object) . cookie.load will automatically analyze it for you.

In my code, I called cookie.save from actions, but you can call it directly in components or any abstraction that you have.

+5
source

I found a working solution.

The trick, unfortunately, is to save the authenticated state in a cookie so that the session state is automatically sent to the server upon request.

+1
source

Source: https://habr.com/ru/post/1239449/


All Articles