react logo
typescript logo
spa
authentication
react router-6

React/TypeScript + React Router 6: Authentication Code Sample

spa
authentication
react router-6
Dan Arias
By Dan Arias, R&D Engineering ManagerLast update on February 8, 2022

This TypeScript code sample demonstrates how to implement authentication in a React Single-Page Application (SPA) that uses React Router 6. This code sample shows you how to integrate React Router 6 with the Auth0 React SDK to create a React application that has both public and private routes.

This React code sample also implements the following security tasks:

  • Add user login and logout.
  • Retrieve user profile information.
  • Make secure calls to an API.

Code Sample Specs

This code sample uses the following main tooling versions:

  • React v17.0.2
  • React Router v6.2.1
  • TypeScript v4.1.2
  • Auth0 React SDK v1.9.0

The React project dependency installations were tested with npm v7.24.0. Running the React application was tested using Node.js v16.10.0.

Quick Auth0 Set Up

First and foremost, if you haven't already, sign up for an Auth0 account to connect your application with the Auth0 Identity Platform.

Next, you'll connect your Single-Page Application (SPA) with Auth0. You'll need to create an application registration in the Auth0 Dashboard and get two configuration values: the Auth0 Domain and the Auth0 Client ID. You'll also need to define an Auth0 Audience value within your project to practice making secure calls to an external API.

Get the Auth0 domain and client ID

  • Open the Applications section of the Auth0 Dashboard.

  • Click on the Create Application button and fill out the form with the following values:

Name
Hello World Client
Application Type
Single Page Web Applications
Single Page Web Applications
  • Click on the Create button.

Visit the "Register Applications" document for more details.

An Auth0 Application page loads up.

As such, click on the "Settings" tab of your Auth0 Application page, locate the "Application URIs" section, and fill in the following values:

Allowed Callback URLs
Allowed Logout URLs
Allowed Web Origins

Scroll down and click the "Save Changes" button.

Next, locate the "Basic Information" section.

Auth0 application settings to enable user authentication

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes it easy to copy and paste code as you follow along. For security, these values are stored in memory and only used locally. They are gone as soon as you refresh the page! As an extra precaution, you should use values from an Auth0 test application instead of a production one.

As such, enter the "Domain" and "Client ID" values in the following fields to set up your single-page application in the next section:

Set Up the React TypeScript Project

Start by cloning the project into your local machine:

git clone https://github.com/auth0-developer-hub/spa_react_typescript_hello-world_react-router-6.git --branch basic-authentication

You are checking out the basic-authentication branch, which holds all the React code related to implementing user login with Auth0.

Make the project directory your current working directory:

cd spa_react_typescript_hello-world_react-router-6

Next, install the React project dependencies:

npm install

Once you have access to the React project, create a .env file under the project directory and populate it as follows:

.env
REACT_APP_AUTH0_DOMAIN=AUTH0-DOMAIN
REACT_APP_AUTH0_CLIENT_ID=AUTH0-CLIENT-ID
REACT_APP_AUTH0_AUDIENCE=https://hello-world.example.com
REACT_APP_API_SERVER_URL=http://localhost:6060

Run the React application by issuing the following command:

npm start

To access the application, you can now visit http://localhost:4040/ to access the application.

Next, click on the "Log In" button, React takes you to the Auth0 Universal Login page. When you use Auth0, you don't need to build any login or sign-up forms!

Your users can log in to your application through a page hosted by Auth0, which provides a secure, standards-based login experience. You can customize the Auth0 login page with your branding and enable different authentication methods, such as logging in with a username/password combination or a social provider like Facebook or Google.

Once you log in, visit the protected "Profile" page, http://localhost:4040/profile, to see all the user profile information that Auth0 securely shares with your application using ID tokens.

Let's see the React Router 6 authentication guard in action. Click on the Log out button and visit the "Profile" page, http://localhost:4040/profile, once again. This time around, React redirects you to log in to the application using the Auth0 Universal Login page.

You can implement this route guard behavior by creating a ProtectedRoute component that integrates with the Auth0 React SDK as follows:

import { withAuthenticationRequired } from "@auth0/auth0-react";
import React, { ComponentType } from "react";
import { Loader } from "./loader";
interface ProtectedRouteProps {
component: ComponentType;
}
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
component,
}) => {
const Component = withAuthenticationRequired(component, {
onRedirecting: () => <Loader />,
});
return <Component />;
};

Then, you can use ProtectedRoute as the element of a React Router 6 Route:

const App: React.FC = () => {
return (
<div className="page-layout">
<NavBar />
<div className="page-layout__content">
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/profile"
element={<ProtectedRoute component={Profile} />}
/>
<Route path="/public" element={<PublicPage />} />
<Route
path="/protected"
element={<ProtectedRoute component={ProtectedPage} />}
/>
<Route
path="/admin"
element={<ProtectedRoute component={AdminPage} />}
/>
<Route path="*" element={<NotFound />} />
</Routes>
</div>
</div>
);
};

The /public, /protected, and /admin pages call an external API using access tokens. Before you can do that, you need to set up and configure an API with Auth0. It'll be quick!

Make Requests to an External API

Let's simulate an essential feature of client applications: requesting data from an API server.

You can pair this client application with an API server that matches the technology stack you use at work. This "Hello World" client application can communicate with any of our "Hello World" API server samples.

You can simulate a secure full-stack application system in no time. Each API server sample gives you clear instructions to quickly get it up and running.

Once set up, you can test the client-server connection using any of the following pages:

Pick an API code sample in your preferred backend framework and language:

actix-web
rust
api
authorization
api
authorization
Actix Web/Rust API: Authorization Code Sample
Code sample of a simple Actix Web server that implements token-based authorization using Auth0.
django
python
api
authorization
api
authorization
Django/Python API: Authorization Code Sample
Code sample of a simple Django server that implements token-based authorization using Auth0.
dot-net
csharp
api
authorization
api
authorization
.NET/C# Web API: Authorization Code Sample
Code sample of a simple .NET server that implements token-based authorization using Auth0.
express
javascript
api
authorization
api
authorization
Express.js/JavaScript API: Authorization Code Sample
Code sample of a simple Express.js server built with JavaScript that implements token-based authorization using Auth0.
express
typescript
api
authorization
api
authorization
Express.js/TypeScript API: Authorization Code Sample
Code sample of a simple Express.js server built with TypeScript that implements token-based authorization using Auth0.
flask
python
api
authorization
api
authorization
Flask/Python API: Authorization Code Sample
Code sample of a simple Flask server that implements token-based authorization using Auth0.
laravel
php
api
authorization
api
authorization
Laravel/PHP API: Authorization Code Sample
Code sample of a simple Laravel server that implements token-based authorization using Auth0.
lumen
php
api
authorization
api
authorization
Lumen/PHP API: Authorization Code Sample
Code sample of a simple Lumen server that implements token-based authorization using Auth0.
phoenix
elixir
api
authorization
api
authorization
Phoenix/Elixir API: Authorization Code Sample
Code sample of a simple Phoenix server that implements token-based authorization using Auth0.
rails
ruby
api
authorization
api
authorization
Ruby on Rails API: Authorization Code Sample
Code sample of a simple Rails server that implements authorization using Auth0.
spring-boot
java
api
authorization
api
authorization
Spring Boot/Java API: Authorization Code Sample
Code sample of a simple Spring Boot server that implements token-based authorization using Auth0.
spring-functional
java
api
authorization
api
authorization
Functional Spring/Java API: Authorization Code Sample
Code sample of a simple Spring API server that follows a functional approach. It implements token-based authorization using Auth0.
standard-library
golang
api
authorization
api
authorization
Golang Web API: Authorization Code Sample
Code sample of a simple Golang server that implements token-based authorization using Auth0.