Skip to main content

Building a site with authentication

With Gatsby, you are able to create restricted areas in your app. For that, you must use the concept of client-only routes.

Using the @reach/router library, which comes installed with Gatsby, you can control which component will be loaded when a certain route is called, and check for the authentication state before serving the content.

Prerequisites

You must know how to set up a basic Gatsby project. If you need to, check the main tutorial.

Setting the authentication workflow

To create a common authentication workflow, you can usually follow these steps:

Real-world example: Gatsby store

The Gatsby store uses this approach when handling a private route:

// import ...
const PrivateRoute = ({ component: Component, ...rest }) => {
  if (
    !isAuthenticated() &&
    isBrowser &&
    window.location.pathname !== `/login`
  ) {
    // If we’re not logged in, redirect to the home page.
    navigate(`/app/login`)
    return null
  }

  return (
    <Router>
      <Component {...rest} />
    </Router>
  )
}

Further reading

If you want more information about authenticated areas with Gatsby, this (non-exhaustive list) may help:


Was this helpful? edit this page on GitHub