Handle State Management in SSR

Learn about state management in an SSR context and the Nuxt “useState” composable.

We'll cover the following

Earlier in this course, we discussed what state management is and how it refers to the process of managing the data or state of an application. However, the discussion seemed to focus on state management because it relates to the client-side context. If it is required to set up state management in an SSR context, the conversation differs a bit.

In SSR, the initial rendering of the application is performed on the server-side. The server generates the HTML content and also the initial state which it sends to the client. This means that the initial state is precomputed on the server and directly available to the client, even before any JavaScript is executed on the client-side. In CSR, both the rendering and state computation are done on the client.

There are multiple libraries that help simplify the complexity of handling state management in SSR, however, given the simplicity of this project, we would be using the Nuxt default useState composable.

The useState composable

The Nuxt documentation defines the useState composable as “an SSR-friendly replacement to ref.” This is largely because the useState composable does exactly what the ref method does. It ensures the reactivity of state data; however, it also preserves the value of the state data from the server-side context to the client-side context.

What does this mean, and how does it affect the user?

In the SPA below containing the survey app project, we implement a route guard for the admin pages, which checks if the user is already logged in before navigating to the admin page. On the client-side, we can set up a regular state management composable using the reactive or ref method to store the user’s authentication state.

However, a challenge arises when using these methods for authentication state during SSR. The server makes an API call using the JWT to confirm its validity. If the token is valid, the server updates the state and begins navigation to the admin page. However, during hydration on the client-side, the client code checks the state value to see the default value. Consequently, it might mistakenly determine that the user isn’t logged in and redirect them to the login page.

Get hands-on with 1200+ tech skills courses.