With traditional Single Page Applications like create-react-app, a common problem is „page flashing“ when trying to redirect a visitor. For example, an authenticated user should be immediately redirected to another page if she tries to access the login route. However, a traditional React app would for a short time still render the login view, as the authentication checks would only be conducted after the first component mount.
This comes to an end with Server Side Rendering (SSR) and this Starter Kit. Before rendering a view, the authentication status of a user is checked and a redirect conducted before the „old“ view is rendered, if necessary. Try it out yourself! Log in and then try to access
/user/login again. Watch the Url bar! Before anything is rendered to the page you will be redirected to the user home page.
How it works
getInitialProps() method is called (because
getServerSideProps() is currently not supported in
_app.tsx). This allows us to fetch the current user from the api before sending a page to the client. This is done by the
authenticateUser function from the
AuthGuard class, which also manages any redirects. As all this takes place before even sending data to the client, we can redirect immediately without any page flashing.