Skip to content

Instantly share code, notes, and snippets.

@twclark0
Forked from gillkyle/add-auth0-recipe.mdx
Last active December 13, 2022 15:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save twclark0/0e11c962743f4e62ccd33a92d8b52d23 to your computer and use it in GitHub Desktop.
Save twclark0/0e11c962743f4e62ccd33a92d8b52d23 to your computer and use it in GitHub Desktop.

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.

<GatsbyPlugin name="gatsby-plugin-auth0" options={{ domain: yourdomain.auth0.com, clientId: s0m3r4nd0mCh4raCT3rZ, }} />


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.

import React from "react"
import { useAuth0 } from "@auth0/auth0-react"
const Account = () => {
const { isAuthenticated, loading, logout, user, loginWithPopup } = useAuth0()
if (loading) {
return <p>Loading...</p>
}
return (
<div>
{isAuthenticated ? (
<>
<button onClick={() => logout()}>Log out</button>
<p>Check out the user data supplied by Auth0, below:</p>
<pre>{isAuthenticated && JSON.stringify(user, null, 2)}</pre>
</>
) : (
<>
<h2>Hi, try logging in:</h2>
<button onClick={() => loginWithPopup()}>Log in</button>
</>
)}
</div>
)
}
export default Account
import React from "react"
import { Auth0Provider } from "@auth0/auth0-react"
import { navigate } from "gatsby"
const onRedirectCallback = appState =>
appState && appState.targetUrl && navigate(appState.targetUrl)
export const wrapRootElement = ({ element }, pluginOptions) => {
return (
<Auth0Provider
domain={pluginOptions.domain}
clientId={pluginOptions.clientId}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{element}
</Auth0Provider>
)
}
@AndrewLamYW
Copy link

AndrewLamYW commented May 17, 2020

Hi, I encountered this error during the first step of running gatsby recipe, how may I solved this? Thank you
"{\"message\":\"Command failed with ENOENT: yarn add -W @auth0/auth0-spa-js@latest\\nspawn yarn ENOENT\",\"installationError\":\"Could not install package\"}"

@anujsachan1990
Copy link

everything works really great, However why My session doesn't persist after a page refresh. So when I land on example-account after logging and getting by user info correctly, but when I refresh the page I lost everything?

@kimbaudi
Copy link

@AndrewLamYW - this gatsby recipe installs @auth0/auth0-spa-js using yarn. So make sure you install yarn globally (i.e., npm i -g yarn) before running this gatsby recipe.

@twclark0
Copy link
Author

everything works really great, However why My session doesn't persist after a page refresh. So when I land on example-account after logging and getting by user info correctly, but when I refresh the page I lost everything?

That is because you need to add the correct domain to "Allowed Web Origins" in the Auth0 application account

@JamieBradders
Copy link

Hi there, thanks for putting this together.
I've just tried to run this as per your Eggheads tutorial and I was presented with an error in step 5 that seems to be breaking the recipe:

│ GatsbyPlugin:                                                                                                                                                                │
│ Install gatsby-plugin-auth0 in gatsby-config.js                                                                                                                              │
│                                                                                                                                                                              │
│ A resource (GatsbyPlugin: {"name":"gatsby-plugin-auth0","options":{"domain":"yourdomain.auth0.com","clientId":"s0m3r4nd0mCh4raCT3rZ"}}) is missing its dependency on         │
│ {"resourceName":"NPMPackage","name":"gatsby-plugin-auth0"}

I appreciate this recipe was posted early 2020 so I'm not sure if something has changed on the gatsby end to cause this? For reference my gatsby version in package.json is "gatsby": "^2.30.1"

@3200pro
Copy link

3200pro commented Jun 8, 2021

Hi there, thanks for putting this together.
I've just tried to run this as per your Eggheads tutorial and I was presented with an error in step 5 that seems to be breaking the recipe:

│ GatsbyPlugin:                                                                                                                                                                │
│ Install gatsby-plugin-auth0 in gatsby-config.js                                                                                                                              │
│                                                                                                                                                                              │
│ A resource (GatsbyPlugin: {"name":"gatsby-plugin-auth0","options":{"domain":"yourdomain.auth0.com","clientId":"s0m3r4nd0mCh4raCT3rZ"}}) is missing its dependency on         │
│ {"resourceName":"NPMPackage","name":"gatsby-plugin-auth0"}

I appreciate this recipe was posted early 2020 so I'm not sure if something has changed on the gatsby end to cause this? For reference my gatsby version in package.json is "gatsby": "^2.30.1"

Can confirm. Using Gatsby 3.0.0 w/ the same problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment