...

/

Implementing a Central Authentication Context

Implementing a Central Authentication Context

Learn to implement a central authentication context for seamless frontend integration with Auth0.

We are going to put state and functions for authentication in a central place in our code. We could use Redux for this, but we are going to take this opportunity to use a context in React.

Note: React context is a standard feature in React that allows components to share data without having to pass it through component properties.

We are going to put our authentication state and functions in a React context that we'll provide to all of the components in our app.

Authentication context implementation in React app

Let's carry out the following steps:

  1. Create a new file in the src folder called Auth.tsx with the following import statements:

Press + to interact
import React from 'react';
import createAuth0Client from '@auth0/auth0-spa-js';
import Auth0Client from '@auth0/auth0-spa-js/dist/
typings/Auth0Client';
import { authSettings } from './AppSettings';
  1. We'll start the implementation by creating a strongly typed context. Add the following code under the import statements in Auth.tsx:

Press + to interact
interface Auth0User {
name: string;
email: string;
}
interface IAuth0Context {
isAuthenticated: boolean;
user?: Auth0User;
signIn: () => void;
signOut: () => void;
loading: boolean;
}
export const Auth0Context = React.
createContext<IAuth0Context>({
isAuthenticated: false,
signIn: () => {},
signOut: () => {},
loading: true
});

So, our context provides properties for whether the user is ...