Protect Frontend Routes and Components (React)

Secure your React components and authenticated routes with the Wristband SDK.

In this section, you'll secure your frontend routes and components during navigation by adding client-side protection with the React Client Auth SDK.

Install the React SDK

Install the React Client Auth SDK using your preferred package manager:

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

Configure the Wristband Auth Provider

Next, initialize the WristbandAuthProvider at the root of your application. This component manages frontend authentication state by automatically fetching user session data from your Session Endpoint. If successful, it stores the session context globally. If the endpoint returns a 401 Unauthorized error, the provider automatically handles the redirect 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.

Create an Auth Provider Wrapper

Because the Next.js App Router defaults to Server Components, you must wrap the client-side WristbandAuthProvider in a custom Client Component. This allows you to safely use React Context within your root layout.

Create a new file for your Client Component wrapper (e.g., src/components/AuthProvider.tsx) and configure the WristbandAuthProvider with your backend URLs:

  • loginUrl: The URL of your application's Login Endpoint.
  • sessionUrl: The URL of your application's Session Endpoint.
// src/components/AuthProvider.tsx

'use client';

import { ReactNode } from 'react';
import { WristbandAuthProvider } from '@wristband/react-client-auth';

export function AuthProvider({ children }: { children: ReactNode }) {
  return (
    <WristbandAuthProvider
      loginUrl="/api/auth/login"
      sessionUrl="/api/auth/session"
    >
      {children}
    </AuthProvider>
  );
}

Add the Provider to Your Root Layout

Finally, wrap your root layout (src/app/layout.tsx) with the new AuthProvider component. This ensures the user's authentication state is verified on the initial page load and remains globally available throughout the entire application.

// src/app/layout.tsx

import { ReactNode } from 'react';
import { AuthProvider } from 'src/components/AuthProvider';
import './globals.css';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <AuthProvider>
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

Protect Frontend Routes and Components

With the WristbandAuthProvider in place, you can now start protecting your routes and components. The React Client Auth SDK provides built-in hooks and utilities for handling common authentication workflows. You can use these to conditionally render views, guard protected routes, and dynamically update your UI based on the user's 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(): Redirects the user to your backend server's Login Endpoint.
  • redirectToLogout(): Redirects the user to your backend server's Logout Endpoint.

The following sections walk through implementing these core authentication workflows.

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

Now let's add server-level protection for your Pages and Server Components so that only authenticated users can access them.

Did this page help you?