Handling Authentication for a Serverside Rendered React Application
Configuring your application to be rendered on the server can add a lot more complexity to the app. Especially if you are adding state management, need to make asynchronous requests to your API and have to set up a development environment with hot reloading.
However creating a server-side rendered react application as opposed to a SPA can be well worth the time and effort, in turn providing many benefits:
- If your application needs to have good SEO, making sure that search engines can crawl and render your page is crucial.
- As opposed to making a request to the server and then letting the browser render the page in a traditional single page app, by initially rendering your react components on the server your initial page load will be a lot faster.
Adding authentication to your SSR React App
Json Web Tokens (JWTs) are commonly used within single page applications to handle authentication. However when it comes to handling authentication for a true universal react app, there is one main issue you will encounter when trying to use JWTs.
A JWT cannot be sent to the server on the initial request.
Now you are probably thinking that there is some way you could attach a JWT to the initial requests header, body or URL however this would not work for one very simple reason.
When a user enters a URL into the address bar and presses enter the browser makes a GET request to that domain and absolutely no information is included within that initial request except for cookies, headers, etc.
So the server would receive the incoming request, however the JWT would not be present because it does not get automatically attached to the request. This means that the server would then need to send a request back to the browser asking it for the JWT to authenticate.
Cookies will however always be tied to the initial request, which is why a cookie based authentication flow must be used for a server-side rendered react application.
I hope this article has helped you decide how to approach authentication for your next SSR react application.