Home

Documentation

Contact

AuthGuard

You might have already realized that the /client/pages/_app.tsx file uses the AuthGuard class in the getInitialProps() function like this:

// _app.tsx

MyApp.getInitialProps = async ({ ctx }) => {
  const req = ctx.req;
  const pathname = ctx.pathname;
  const res = ctx.res;

  if (!req || !pathname || !res) {
    return {};
  }

  // AuthGuard
  const authenticator = new AuthGuard();

  return await authenticator.authenticateUser(req, res, pathname);
};

This class is located under /client/services/Auth/AuthGuard.tsx.

The AuthGuard is responsible for authenticating a user server side via the request cookies. This is done in order to avoid page flashing. You might have experienced this problem in other React frameworks like create-react-app, where a client is only redirected to another view after a short display of the original route. However, as we use Next.js with server side rendering, we have the possibility to redirect the client to another route before rendering a page. This is not only more secure but also increases the user experience.

The heavy lifting is done in AuthGuard.authenticateUser(), which takes the request and response object as well as the pathname as arguments. It extracts the cookies from the request in order to retrieve the Laravel session tokens. It then sends a request to the Laravel API to check the authentication status. After receiving a response, the method checks if the client tries to access a protected route. Depending on the authentication status we get from the API, the user will be redirected if necessary.