The simplest way to add authentication to your React app. Handles everything for you. Users, login forms, redirects, sharing state between components. Everything
How to use useAuth
useAuth
is designed to be quick to setup. You'll need an Auth0 account with an app domain and client id.
1. Install the hook
$ yarn add react-use-auth
Downloads from npm, adds to your package.json, etc. You can use npm
as well.
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.
// gatsby-browser.js
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="GjWNFNOHq1ino7lQNJBwEywa1aYtbIzh"
>
{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 workauth0_domain
– from your Auth0 appauth0_client_id
– from your Auth0 appauth0_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_audience_domain