Add Authentication with Auth0 to a Gatsby site
All the pieces of authentication are possible in Gatsby. Thanks to Auth0, setting it up doesn't have to be so cumbersome!
This setup comes straight from Auth0's official quick start for React.
The first step is installing the official Auth0 SDK for React from npm.
Auth0's React SDK provides some nice functions to access the user and silently reauthenticate them on your site.
The npm package let's you destructure values and functions that include working with:
- access tokens - using functions like getIdTokenClaims and getTokenSilently
- access user data - using the user object
- check the authenticated state - using isAuthenticated
- see if Auth0 is still initializing - using the loading boolean
The next recipe step will ask you to add it.
To wrap your app in the Auth0 provider (how the magic works for using with the React SDK npm package, this recipe will generate a new local plugin.
The package.json file is needed for plugins:
Inside of gatsby-browser we will wrap out app with the auth provider given to use by the SDK. A provider comes from React's context API and allows access to data or functions in any component or file in your app below it in the React tree. This gives the rest of your app access to authentication information and functionality.
Now, with the code added, you can install the local plugin in your Gatsby config. The options for domain and clientId are passed in.
You will need to replace the values with your own Auth0 app's client id and domain. The example values will not work until you change them.
On the Auth0 side, all you need to ensure is that you have created an app and within that app you have added http://localhost:8000 to Allowed Callback URLs, Allowed Logout URLs, and Allowed Web Origins.
To test that it's working, this recipe will add an example page at http://localhost:8000/example-account where you can test by clicking on the login button, which will redirect you to Auth0's hosted login page.
You will see a user logged in the console when you login, and can use the useAuth0 hook by importing it from the SDK package on any page or in any componoent.