2. Set up AuthProvider

useAuth uses an AuthProvider component to configure the Auth0 client and share state between components. It's using React context with a reducer behind the scenes, but that's an implementation detail.

I recommend adding this around your root component. In Gatsby that's done in gatsby-browser.js and gatsby-ssr.js. Yes useAuth is built so it doesn't break server-side rendering. ✌️

But of course server-side "you" will always be logged out.

import React from "react"
import { navigate } from "gatsby"
import { AuthProvider } from "react-use-auth"
export const wrapRootElement = ({ element }) => (
<AuthProvider
navigate={navigate}
auth0_domain="useauth.auth0.com"
auth0_client_id="GjWNFNOHqlino7lQNjBwEywalaYtbIzh"
>
{element}
</AuthProvider>
)

<AuthProvider> creates a context, sets up a state reducer, initializes an Auth0 client and so on. Everything you need for authentication to work in your whole app :)

The API takes a couple config options:

navigate – your navigation function, used for redirects. I've tested with Gatsby, but anything should work

auth0_domain – from your Auth0 app

auth0_client_id – from your Auth0 app

auth0_params – an object that lets you overwrite any of the default Auth0 client parameters

PS: even though Auth doesn't do anything server-side, useAuth will throw errors during build, if its context doesn't exist

Default Auth0 params

By default useAuth's Auth0 client uses these params:

const params = {
domain: auth0_domain,
clientID: auth0_client_id,
redirectUri: `${callback_domain}/auth0_callback`,
audience: `https://${auth0_domain}/api/v2/`,
responseType: "token id_token",
scope: "openid profile email"
}

domain and clientID come from your props.

redirectUri is set to use the auth0_callbackpage on the current domain. Auth0 redirects here after users login so you can set cookies and stuff. useAuthwill handle this for you ✌️

audience is set to use api/v2. I know this is necessary but honestly have been copypasting it through several of my projects.

responseType same here. I copy paste this from old projects so I figured it's a good default.

scope you need openid for social logins and to be able to fetch user profiles after authentication. Profile and Email too. You can add more via the auth0_params override.