Skip to main content
← Guides

Guide

How to Add Authentication to Any React App in 2026

Updated PkgPulse Team5 min read
0

Add authentication to a React SPA or Next.js app. Choose managed Clerk or self-hosted Auth.js, then verify sessions and protect your API routes.

Contents

TL;DR

Choose the auth setup that fits your server. For a React SPA with a separate API, use a React SDK for sign-in and verify the session at the API. Clerk provides both client and server integrations. For an existing Next.js app that runs its own auth, use the Auth.js setup for your installed NextAuth version. In either case, the first check is a protected API request. It should deny an anonymous request and allow the same request after sign-in for a user with access.

Key Takeaways

  • React shows sign-in state. Your API decides whether the user can read or change data.
  • Auth.js supports JWT or database sessions. Choose based on how you deploy the API and when you need access changes to take effect.
  • Lucia's npm library is deprecated. Use its material as a reference if you maintain a custom session implementation.

Choose your approach

AppStart withWhat the server owns
React SPA and an APIClerk React SDK or the browser integration for your auth serviceVerify the session with the matching backend integration and authorize the request
Next.js App Router and managed identityClerk Next.js SDKCheck route and resource access in server code
Existing Next.js app with self-hosted authAuth.js and a compatible provider or adapterRun the auth handler, configure secrets and authorize the session
Existing custom sessionsDocument the cookie and session contract before changing librariesCreate, verify, expire and revoke sessions

A static React deployment cannot validate a user's access to private data by itself. Keep the session verifier in the service that reads or writes the data. Decide how the browser reaches that service before you choose an integration. A same-origin API and a separate-origin API have different cookie and request configuration.

Option 1. Clerk for a React SPA

Follow the Clerk React quickstart for your React package and bundler. With Vite, put the publishable key in VITE_CLERK_PUBLISHABLE_KEY. Vite exposes that value to the browser. Put the Clerk secret key in your API's server environment. Wrap the application in ClerkProvider and render the sign-in control or route appropriate for your app.

import { ClerkProvider, Show, SignInButton, UserButton } from '@clerk/react';

const publishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;

export function App() {
  return (
    <ClerkProvider publishableKey={publishableKey}>
      <Show when="signed-out"><SignInButton /></Show>
      <Show when="signed-in"><UserButton /></Show>
    </ClerkProvider>
  );
}

This UI example assumes you have configured a Clerk application and installed its React SDK. Use the Clerk request authentication guide for your API. Follow the same-origin or cross-origin path that matches your deployment. Check the API for an unsigned request and for a signed-in request before wiring up the rest of the UI. If you use Next.js, use the server helpers from @clerk/nextjs/server with clerkMiddleware() and the documented Next.js matcher.

Option 2. Auth.js for an existing Next.js app

This App Router example uses the Auth.js v5 beta interface. For a fresh installation, run npm install next-auth@beta. The npm latest tag still points to NextAuth v4. Check your lockfile before applying the example, and keep your existing setup if it serves the app. For a new self-hosted project, the Auth.js maintainers also document migration to Better Auth. Evaluate the session and deployment requirements before choosing between the two.

// auth.ts
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';

export const { auth, handlers, signIn, signOut } = NextAuth({
  providers: [GitHub],
  session: { strategy: 'jwt' },
});

Set AUTH_SECRET, AUTH_GITHUB_ID and AUTH_GITHUB_SECRET on the server. In your GitHub OAuth app, register your deployment origin followed by /api/auth/callback/github as its authorization callback URL. Auth.js GitHub provider Then expose the auth route by importing the handlers and exporting both HTTP methods.

// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth';

export const { GET, POST } = handlers;

To try the provider on staging, open /api/auth/signin and choose GitHub. Complete the provider’s sign-in flow and check /api/auth/session for the signed-in user. This walkthrough illustrates the provider step. The local fixture below covers anonymous access.

Add a protected API route before you ship the sign-in button. This small example checks for a session and returns the current user's name. For an endpoint that loads records, check resource access after the session check and before the database read or write.

// app/api/me/route.ts
import { auth } from '@/auth';

export async function GET() {
  const session = await auth();
  if (!session?.user) return new Response(null, { status: 401 });

  return Response.json({ name: session.user.name });
}

Existing Lucia deployments

Lucia's maintainer deprecated the library and now publishes implementation references. If your application still imports the package, inventory the session table, cookie attributes, expiry, authorization checks and sign-out behavior before replacing it. Decide whether to end existing sessions during migration or add a transition for them. Exercise the new and old session behavior in staging and document how to roll back.

JWT and database sessions

With a database session, a cookie refers to server-side session state. Your application can invalidate the session by removing or marking the record, then rejecting it on subsequent requests. With a JWT strategy, the server can validate an issued token without a session database. To cut off a token before its normal expiry, you need a revocation mechanism or a check of current access.

Auth.js defaults to JWT sessions without a database adapter and database sessions if you configure an adapter, unless you set the strategy explicitly. Test what happens when an account loses access or a user signs out from another device. A token that still verifies may represent a user whose access to a particular project has changed.

Verify sign-in, expiry and access

Start on a deployed staging domain so redirect URLs, secure cookies and server environment variables behave like production. Sign in from the page users actually open. Follow the callback back to the application, refresh a protected page and call the API that powers it. Confirm the response belongs to the signed-in account. Repeat after sign-out and after a session expires.

Test an action that changes data separately from a read. The server should confirm the session, check that the user has access to the resource and enforce the expected limits on the action. If your app supports multiple workspaces, exercise the same request before and after changing workspace. When evaluating different providers, repeat these checks for the configured providers and their callback URLs.

Methodology

The local fixture exercises anonymous access to the protected Next.js API route with the Auth.js v5 beta config. The Clerk example illustrates the browser setup. Complete provider callbacks, session expiry and app-specific permissions on your staging deployment.

Source notes