Protect Frontend Routes and Components (React)

Learn how to protect authenticated routes and componentes using Wristband's React SDK.

This section shows how to use the React Client Auth SDK to secure frontend routes and components that need login access.

Install the React SDK

Install the React Client Auth SDK with your preferred package manager CLI:

npm install @wristband/react-client-auth
yarn add @wristband/react-client-auth
pnpm add @wristband/react-client-auth

Configure the Wristband Auth Provider

Wrap your application with WristbandAuthProvider to manage frontend authentication state.

This component calls your backend Session Endpoint to check for a valid session. If successful, it stores the session data in React Context. If the backend returns a 401 Unauthorizedresponse, the provider automatically redirects the user to your Login Endpoint.

📘

Disabling Automatic Redirects

You can configure the WristbandAuthProvider to not redirect to the Login Endpoint when it receives a 401 Unauthorized response from the Session Endpoint by setting disableRedirectOnUnauthenticated=true.

When redirects are disabled, use the isAuthenticated state returned by the useWristbandAuth hook to determine whether the user is logged in.

Configure WristbandAuthProvider at your app root by providing these two URLs:

  • loginUrl: Your backend Login Endpoint URL.
  • sessionUrl: Your backend Session Endpoint URL.

Placing WristbandAuthProvider at the root ensures the user's login state verifies immediately on load and stays available everywhere.

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { WristbandAuthProvider } from '@wristband/react-client-auth';

import './index.css';

import { App } from 'app';

const root = createRoot(document.getElementById('root'));

root.render(
  <StrictMode>
    <WristbandAuthProvider
      loginUrl='<your-login-endpoint-url>'
      sessionUrl='<your-session-endpoint-url>'
    >
      <App />
    </WristbandAuthProvider>
  </StrictMode>
);

Protect Frontend Routes and Components

After configuring WristbandAuthProvider, you can secure your routes and components using the SDK's built-in hooks and utilities.

These tools support common authentication patterns:

  • Conditional rendering of public and private views.
  • Route protection for restricted pages.
  • Dynamic UI updates based on login status.

Hooks

  • useWristbandAuth(): Access the user's authentication status throughout your app.
  • useWristbandSession(): Access user data returned from your backend server's Session Endpoint.

Utility Functions

  • redirectToLogin(): This action sends the user to the login page on your server.
  • redirectToLogout(): This action sends the user to the logout page on your server.

The following sections demonstrate how to build common authentication flows with these functions and hooks.

Pattern 1: Conditional Rendering Based on User's Auth State

import React from 'react';
import {
  useWristbandAuth, useWristbandSession, redirectToLogin, redirectToLogout
} from '@wristband/react-client-auth';

function App() {
  const { isAuthenticated, isLoading } = useWristbandAuth();
  const { userId, tenantId } = useWristbandSession();
  
  if (isLoading) {
    return <div>Loading...</div>;
  }

  const AuthenticatedView = () => (
    <>
      <h1>Welcome to Wristband Auth</h1>
      <p>Your User ID: USERID</p>
      <p>Your Tenant ID: {tenantId}</p>
      <button onClick={() => redirectToLogout('<your-logout-endpoint-url>')}>
        Logout
      </button>
    </>
  );
  const UnauthenticatedView = () => (
    <>
      <h1>Welcome to Wristband Auth</h1>
      <button onClick={() => redirectToLogin('<your-login-endpoint-url>')}>
        Login
      </button>
    </>
  );

  return (
    <div>
      {isAuthenticated ? <AuthenticatedView /> : <UnauthenticatedView />}
    </div>
  );
};

export default App;

Pattern 2: Protect Explicit Routes with an Auth Guard Component

import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useWristbandAuth } from '@wristband/react-client-auth';

import { Dashboard, Login } from '@/components';

const AuthGuard = ({ children }: { children: React.ReactNode }) => {
  const { isAuthenticated, isLoading } = useWristbandAuth();
  
  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (!isAuthenticated) {
    return <Navigate to="<your-login-endpoint-path>" replace />;
  }

  return children;
};

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="<your-login-endpoint-path>" element={<Login />} />
        <Route
          path="/dashboard"
          element={
            <AuthGuard>
              <Dashboard />
            </AuthGuard>
          }
        />
      </Routes>
    </BrowserRouter>
  );
}

export default App;


What’s Next

Once you've finished securing your frontend routes and components, the next step is to protect your backend endpoints.

Did this page help you?