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:
- Create client-only routes, to tell Gatsby which routes should be rendered on demand
- Wrap private content in a PrivateRoute component, to check if a user is authenticated or not, therefore rendering the content or redirecting to another page (usually, the login page)
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:
- Making a site with user authentication, a Gatsby advanced tutorial
- Gatsby repo simple auth example
- A Gatsby email application, using React Context API to handle authentication
- The Gatsby store for swag and other Gatsby goodies
- Add Authentication to your Gatsby apps with Auth0 (livestream with Jason Lengstorf)
Edit this page on GitHub