The Problem: Your React App Is an Open Book
Open your browser's DevTools right now. Go to any React SPA. Click the Network tab. Watch the requests fly.
GET https://api.your-backend.com/api/v1/users/
Authorization: Token abc123def456...
Content-Type: application/json
There it is. Everything an attacker needs:
- Your backend URL — They know exactly where your server lives
- Your authentication token — They can copy-paste it and impersonate you
- Your API structure — They can map every endpoint, every parameter
- Your error responses — They learn what validation rules you enforce
In a traditional React app, the browser is a glass box. Everything is visible. Everything is copyable. I've always wondered: Is there a way to hide this? The answer is yes. And it's built into Next.js.
The Core Insight: Your Server as an API Gateway
The fundamental idea is simple: the browser should never talk directly to your backend.
Instead:
Browser ──────▶ Your Next.js Server ──────▶ Your Backend
│ │ │
│ │ │
"I need Injects Returns
/api/v1/users" auth token real data
│ │ │
│◀───────────────────│◀─────────────────────│
│ Returns proxied
│ response
The browser only sees your Next.js server. The backend URL? Invisible. The auth token? Never leaves the server. The API structure? Completely obscured.
Let's build this.
Architecture: The Four Pillars
This security architecture rests on four pillars:
┌─────────────────────────────────────────────────────────────┐
│ SECURITY ARCHITECTURE │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. ENVIRONMENT ISOLATION │
│ Server-only env vars vs client-safe env vars │
│ │
│ 2. SERVER-SIDE PROXY │
│ Catch-all route that injects auth │
│ │
│ 3. ENCRYPTED TOKEN STORAGE │
│ HTTP-only cookies via NextAuth JWT │
│ │
│ 4. AUTH FAILURE INTERCEPTION │
│ Graceful handling without leaking details │
│ │
└─────────────────────────────────────────────────────────────┘
Let's dissect each one.
Pillar 1: Environment Isolation
The first rule of invisible authentication: the backend URL must never reach the browser.
The Setup
# .env (server-only — never exposed to browser) API_BASE_URL=https://your-backend.com/api/v1 AUTH_SECRET=your-jwt-encryption-key # .env.local (client-safe — exposed to browser) NEXT_PUBLIC_API_BASE_URL=/api/v1 NEXT_PUBLIC_DEBUG=false
The magic is in the naming convention:
API_BASE_URL— NoNEXT_PUBLIC_prefix → server-onlyNEXT_PUBLIC_API_BASE_URL—NEXT_PUBLIC_prefix → bundled into client code
Next.js strips all non-NEXT_PUBLIC_ environment variables from the client bundle during build time. If you try to access process.env.API_BASE_URL in a client component, you'll get undefined.
The Dual-Mode API Client
Here's where it gets interesting. Your ApiClient needs to behave differently depending on where it runs:
// src/core/data/api-client.ts const BASE_URL = typeof window === "undefined" ? (process.env.API_BASE_URL || "http://localhost:8000/api/v1") : (process.env.NEXT_PUBLIC_API_BASE_URL || "/api/v1"); function isClient(): boolean { return typeof window !== "undefined"; }
Server-side (Node.js, no window):
typeof window === "undefined"→true- Uses
API_BASE_URL→https://your-backend.com/api/v1 - Talks directly to the real backend
Client-side (browser, window exists):
typeof window === "undefined"→false- Uses
NEXT_PUBLIC_API_BASE_URL→/api/v1 - Talks to your Next.js proxy (which then talks to the backend)
This is the foundation. Everything else builds on top of it.
Pillar 2: The Server-Side Proxy
This is the heart of the architecture. A single Next.js catch-all route that intercepts all /api/v1/* requests and proxies them to your backend.
The Implementation
// src/app/api/v1/[...path]/route.ts import { NextRequest, NextResponse } from "next/server" import { auth } from "@/features/auth/infrastructure/auth.config" const BACKEND_URL = process.env.API_BASE_URL async function proxy(request: NextRequest, path: string[]) { // Step 1: Validate session (reads encrypted JWT from cookie) const session = await auth() if (!session?.accessToken) { return NextResponse.json( { detail: "Authentication required" }, { status: 401 } ) } if (!BACKEND_URL) { return NextResponse.json( { detail: "Backend URL not configured" }, { status: 500 } ) } // Step 2: Reconstruct backend URL from path segments const pathname = path.join("/") const url = `${BACKEND_URL}/${pathname}${pathname.endsWith("/") ? "" : "/"}${request.nextUrl.search}` // Step 3: Inject authentication token (client never sends this!) const headers = new Headers(request.headers) headers.set("Authorization", `Token ${session.accessToken}`) headers.delete("host") // Prevent host-header attacks // Step 4: Forward request to real backend try { const body = ["GET", "HEAD"].includes(request.method) ? undefined : await request.arrayBuffer() const response = await fetch(url, { method: request.method, headers, body, } as RequestInit) // Step 5: Handle auth failures gracefully if (response.status === 403) { const data = await response.clone().json().catch(() => null) if (data?.detail?.includes("Invalid authentication")) { return NextResponse.json( { detail: data.detail }, { status: 401 } ) } } // Step 6: Return proxied response return new NextResponse(response.body, { status: response.status, statusText: response.statusText, headers: response.headers, }) } catch (error) { console.error(`Proxy error for ${request.method} ${url}:`, error) return NextResponse.json( { detail: "Upstream server error" }, { status: 502 } ) } } // Export handlers for all HTTP methods export async function GET(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { return proxy(request, (await params).path) } export async function POST(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { return proxy(request, (await params).path) } export async function PUT(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { return proxy(request, (await params).path) } export async function PATCH(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { return proxy(request, (await params).path) } export async function DELETE(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { return proxy(request, (await params).path) }
What This Does
-
Session Validation: Reads the encrypted JWT from the HTTP-only cookie using
auth(). No token in request headers — it's in the cookie. -
URL Reconstruction: Takes the path segments from
/api/v1/admin/users/and reconstructs the full backend URL:https://your-backend.com/api/v1/admin/users/ -
Token Injection: Sets the
Authorizationheader on the server-side request. The client never sends this header. -
Host Header Sanitization: Deletes the
hostheader to prevent host-header injection attacks. -
Body Forwarding: Supports all content types by reading the request body as an
ArrayBuffer. -
Auth Failure Mapping: Converts 403 "Invalid authentication" responses to 401, so the client can handle them consistently.
-
Error Isolation: Catches fetch errors and returns a generic 502 "Upstream server error" — never exposing backend details.
Pillar 3: Encrypted Token Storage
The token is stored in an encrypted JWT cookie using NextAuth. The client never sees the raw token.
The Authentication Flow
// src/features/auth/infrastructure/auth.config.ts import NextAuth, { CredentialsSignin } from "next-auth"; import Credentials from "next-auth/providers/credentials"; export const { handlers, auth, signIn, signOut } = NextAuth({ providers: [ Credentials({ name: "credentials", credentials: { email: { label: "Email", type: "email" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { if (!credentials?.email || !credentials?.password) return null; try { const api = new ApiClient(); const repo = new ApiAuthRepository(api); const { token, user } = await repo.login({ email: credentials.email as string, password: credentials.password as string, }); return { id: user.id, email: user.email, name: user.name, emailVerified: null, accessToken: token.access, // ← Goes into JWT refreshToken: token.refresh, // ← Goes into JWT isSuperuser: true, }; } catch (err) { if (err instanceof ApiClientError) { const message = typeof err.data === "string" ? err.data : (err.data as Record<string, unknown>)?.detail; const error = new CredentialsSignin(); error.code = (message as string) ?? "Invalid credentials"; throw error; } return null; } }, }), ], callbacks: { // Store tokens in encrypted JWT async jwt({ token, user }) { if (user) { token.accessToken = (user as unknown as Record<string, unknown>).accessToken as string; token.refreshToken = (user as unknown as Record<string, unknown>).refreshToken as string | undefined; token.isSuperuser = true; } return token; }, // Expose only what's needed to session async session({ session, token }) { session.accessToken = token.accessToken as string; if (session.user) { (session.user as unknown as Record<string, unknown>).isSuperuser = token.isSuperuser; } return session; }, }, pages: { signIn: "/login", }, trustHost: true, }); // Type augmentations declare module "next-auth" { interface Session { accessToken: string; } interface User { accessToken: string; refreshToken?: string; isSuperuser: boolean; } } declare module "@auth/core/jwt" { interface JWT { accessToken: string; refreshToken?: string; isSuperuser: boolean; } }
What the Client Sees
Cookie: next-auth.session-token=eyJhbGciOiJIUzI1NiJ9.eyJhY2Nlc3NUb2tlbiI6...
What's Inside (Encrypted)
{ "accessToken": "abc123...", "refreshToken": "xyz789...", "email": "admin@example.com", "isSuperuser": true }
The token is encrypted using AUTH_SECRET. Even if someone steals the cookie, they can't decrypt it without the secret. And the secret is server-only — it's never exposed to the browser.
Pillar 4: Auth Failure Interception
When authentication fails, the system handles it gracefully without leaking sensitive information.
The ApiClient Interceptor
// src/core/data/api-client.ts (excerpt) this.instance.interceptors.response.use( (response) => response, async (error: AxiosError<ApiErrorDetail>) => { const status = error.response?.status; const data = error.response?.data; const isAuthFailure = status === 401 || (status === 403 && typeof data === "object" && data !== null && "detail" in data && typeof (data as Record<string, unknown>).detail === "string" && ((data as Record<string, unknown>).detail as string).includes("Invalid authentication")); if (isAuthFailure) { if (isClient()) { // Client-side: Redirect to login void signOut({ callbackUrl: "/login" }); } else { // Server-side: Throw error for requireAuth to handle throw new AuthenticationExpiredError(); } } return Promise.reject(this.normalizeError(error)); }, );
The Server-Side Guard
// src/core/data/require-auth.ts import { redirect } from "next/navigation"; import { AuthenticationExpiredError } from "./api-client"; export function requireAuth(error: unknown): void { if (error instanceof AuthenticationExpiredError) { redirect("/signout"); } }
Usage in Server Components
Every dashboard page uses this pattern:
// src/app/(dashboard)/page.tsx import { auth } from "@/features/auth/infrastructure/auth.config" import { ApiOverviewRepository } from "@/features/overview/infrastructure/api-overview-repository" import { GetOverviewUseCase } from "@/features/overview/application/get-overview-use-case" import { requireAuth } from "@/core/data" export default async function Page() { const session = await auth() const token = session?.accessToken if (!token) { return <p className="text-sm text-ink-muted">Unauthorized</p> } const repository = new ApiOverviewRepository(token) const data = await new GetOverviewUseCase(repository).execute().catch(async (e) => { await requireAuth(e) return emptyOverview }) return <OverviewPage stats={data.stats} ... /> }
The pattern is:
- Get session from
auth() - Extract token
- Make API call
- Catch errors →
requireAuth(e)redirects to/signoutif token expired
The Complete Flow
Let's trace a request from browser to backend:
┌─────────────────────────────────────────────────────────────┐
│ REQUEST FLOW │
├─────────────────────────────────────────────────────────────┤
│ │
│ BROWSER │
│ ├─ User clicks "Load Users" │
│ ├─ React component calls: │
│ │ fetch("/api/v1/admin/users/") │
│ │ (No auth header — cookie sent automatically) │
│ │ │
│ NEXT.JS SERVER │
│ ├─ Route: /api/v1/[...path]/route.ts │
│ ├─ auth() reads HTTP-only cookie │
│ ├─ Decrypts JWT using AUTH_SECRET │
│ ├─ Extracts accessToken │
│ ├─ Sets header: Authorization: Token <accessToken> │
│ ├─ Deletes host header │
│ │ │
│ BACKEND │
│ ├─ Receives: GET https://backend.com/api/v1/admin/users/ │
│ ├─ Headers: Authorization: Token <real-token> │
│ ├─ Returns: { users: [...] } │
│ │ │
│ NEXT.JS SERVER │
│ ├─ Receives backend response │
│ ├─ Returns to browser: { users: [...] } │
│ │ │
│ BROWSER │
│ ├─ Receives data │
│ ├─ Network tab shows: │
│ │ GET /api/v1/admin/users/ → 200 OK │
│ │ (No backend URL, no token visible) │
│ │
└─────────────────────────────────────────────────────────────┘
What Attackers See vs. Reality
What's Visible in Network Tab
Request: GET /api/v1/admin/users/
Response: { "users": [...] }
That's it. No backend URL. No token. No API structure.
What's Actually Happening
Browser → /api/v1/admin/users/
↓
Next.js Server reads cookie
↓
Decrypts JWT, extracts token
↓
Forwards to: https://your-backend.com/api/v1/admin/users/
↓
Injects: Authorization: Token abc123...
↓
Returns response to browser
Security Comparison
The Defense-in-Depth Model
┌─────────────────────────────────────────────────────────────┐
│ DEFENSE LAYERS │
├─────────────────────────────────────────────────────────────┤
│ │
│ LAYER 1: ENVIRONMENT ISOLATION │
│ └─ Backend URL never reaches browser │
│ │
│ LAYER 2: SERVER-SIDE PROXY │
│ └─ Auth token injected server-side │
│ │
│ LAYER 3: ENCRYPTED COOKIES │
│ └─ Token stored in HTTP-only, encrypted cookie │
│ │
│ LAYER 4: HOST HEADER SANITIZATION │
│ └─ Prevents host-header injection attacks │
│ │
│ LAYER 5: AUTH FAILURE INTERCEPTION │
│ └─ Graceful handling without leaking details │
│ │
│ LAYER 6: SENSITIVE DATA REDACTION │
│ └─ Never log tokens, passwords, or secrets │
│ │
│ LAYER 7: ROUTE PROTECTION │
│ └─ Unauthenticated users redirected to /login │
│ │
└─────────────────────────────────────────────────────────────┘
Sensitive Data Redaction
Even in logs, sensitive data is never exposed:
// src/core/data/api-client.ts function redact(body: unknown): unknown { if (!body || typeof body !== "object") return body; const clone = { ...(body as Record<string, unknown>) }; for (const key of ["password", "token", "secret", "key", "authorization"]) { if (key in clone) clone[key] = "***"; } return clone; }
Every request/response is logged through redact():
this.instance.interceptors.request.use( (config) => { if (config.data) logger.debug("body", redact(config.data)); return config; }, // ... );
Before redaction:
{ "email": "admin@example.com", "password": "supersecret123", "token": "abc123..." }
After redaction:
{ "email": "admin@example.com", "password": "***", "token": "***" }
Route Protection
The middleware (or proxy) ensures unauthenticated users can't access protected routes:
// src/proxy.ts import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { auth } from "@/features/auth/infrastructure/auth.config"; export async function proxy(request: NextRequest) { const session = await auth(); const isLoggedIn = !!session?.user; const { pathname } = request.nextUrl; const isAuthPage = pathname.startsWith("/login"); const isApiAuthRoute = pathname.startsWith("/api/auth"); const isStaticFile = pathname.startsWith("/_next") || pathname === "/favicon.ico"; // Allow static files and auth routes if (isStaticFile || isApiAuthRoute) { return NextResponse.next(); } // Redirect logged-in users away from login page if (isAuthPage) { if (isLoggedIn) { return NextResponse.redirect(new URL("/", request.url)); } return NextResponse.next(); } // Redirect unauthenticated users to login if (!isLoggedIn) { const loginUrl = new URL("/login", request.url); loginUrl.searchParams.set("callbackUrl", pathname); return NextResponse.redirect(loginUrl); } return NextResponse.next(); } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], };
Key Takeaways
-
Never expose backend URLs — Use server-only environment variables (
API_BASE_URLwithoutNEXT_PUBLIC_prefix) -
Proxy all API requests — Let Next.js inject authentication via a catch-all route handler
-
Encrypt tokens in HTTP-only cookies — Not localStorage, not sessionStorage, not in request headers from the client
-
Redact sensitive data in logs — Never log passwords, tokens, or secrets
-
Handle auth failures gracefully — Redirect to login without leaking error details
-
Sanitize headers — Delete the
hostheader to prevent host-header attacks -
Use type augmentations — Extend NextAuth types to ensure type safety across your codebase
The Result
Your frontend becomes a black box to outsiders. They see a Next.js app making requests to /api/v1/.... They don't know:
- Where your backend lives
- How authentication works
- What your API structure looks like
- What tokens are being used
That's the Next.js superpower. Your server becomes your API gateway, and your backend becomes invisible.
What's Next
In the next post in this series, we'll explore another Next.js superpower: Server Components as a Data Fetching Layer — how to fetch data securely without exposing your data layer to the client.
This post is part of the "Next.js Superpowers" series, exploring hidden capabilities that make Next.js special for building secure, performant web applications.





