Normally, when I started my full-stack development journey, I designed and developed API endpoints along with client-side routes and pages. However, not all routes and delivered pages are intended for visitors. Many of them are specifically designed for logged-in users, more precisely, authenticated users.

My approach to protecting these routes was mainly based on:

"DOM Content Loaded Provoked Protected API Check"

"useEffect Triggered checkAuth Functions" → Auth Context Provider & Protected Routes Provider

However, both of these methods have their own drawbacks.

Limitations of Client-Side Authentication

The first approach can cause the following scenarios:

Scenario Result
Unauthenticated user opens dashboard Redirected to login
Authenticated user opens dashboard Dashboard loads
User manually changes URL Authentication check runs again
User disables JavaScript Client-side authentication check never runs
User inspects HTML source Can see the HTML delivered to the browser
User directly calls a protected API Backend must independently authenticate the request

The second approach, being part of the React component tree, also runs on the client side. Depending on the implementation and fetching logic, components may render briefly before the authentication check completes, potentially exposing protected content.

To handle this flow effectively, additional redirects, loading screens, and spinner screens are required.

Introducing Next.js Proxy

Whereas Proxy is much more similar to an authentication middleware, which now uses proxy.ts (formerly middleware.ts). Although Middleware is deprecated in Next.js 16 and has been renamed to Proxy, it now uses the Node.js runtime instead of the Edge Runtime by default, allowing compatibility with Node.js-specific APIs and libraries.

How Does Proxy Work?

import { NextRequest, NextResponse } from "next/server"; const SESSION_COOKIE_NAME = process.env.NODE_ENV === "production" ? "__Host-crimexis_session" : "crimexis_session"; const PROTECTED_PATHS = [ "/Dashboard", "/CrimeLogs", "/Hotspots", "/AddCrime", "/Settings", "/Account", ]; const AUTH_PATHS = ["/Login", "/Register"]; export function proxy(req: NextRequest) { const { pathname } = req.nextUrl; const hasSessionCookie = Boolean( req.cookies.get(SESSION_COOKIE_NAME)?.value ); const isProtected = PROTECTED_PATHS.some( (p) => pathname === p || pathname.startsWith(`${p}/`) ); if (isProtected && !hasSessionCookie) { const loginUrl = new URL("/Login", req.url); loginUrl.searchParams.set("next", pathname); return NextResponse.redirect(loginUrl); } const isAuthPage = AUTH_PATHS.some( (p) => pathname === p || pathname.startsWith(`${p}/`) ); if (isAuthPage && hasSessionCookie) { return NextResponse.redirect( new URL("/Dashboard", req.url) ); } return NextResponse.next(); } export const config = { matcher: [ "/Dashboard/:path*", "/CrimeLogs/:path*", "/Hotspots/:path*", "/AddCrime/:path*", "/Settings/:path*", "/Account/:path*", "/Login", "/Register", ], }; 

Moving Beyond Next.js: The Separate Backend Approach

However, there is one more aspect of this architecture.

What if we choose Next.js solely for the client-facing application and run our backend in a completely separate Node.js runtime, which handles all database connections, authentication, and session management?

In that case, our authentication checks and session records must be verified by the Node.js backend rather than relying solely on the Next.js server.

Next.js must still be effectively used in this architecture. This is where I learned about the Backend for Frontend (BFF) pattern.

Understanding the Backend for Frontend (BFF) Architecture

The actual idea of this pattern is:

Your Next.js application becomes the secure gateway between client devices and your actual Node.js backend.

This can enhance security in the following ways:

The browser never needs to know about Node.js access tokens, refresh tokens, or internal authentication mechanisms. Instead, it communicates with Next.js, and then Next.js communicates with your Node.js backend.

Implementing BFF Architecture in Crimexis

For its implementation, I picked up my project Crimexis.

I upgraded my Next.js application to v16 and set up a Backend for Frontend gateway in front of my Express backend.

Now, the browser does not communicate directly with my backend. Instead, all client-side API requests go through server-side components running within Next.js, particularly BFF API routes.

This also allows Server Components to communicate with the backend directly through a server-only backend client when required.

BFF Architecture — Next.js Proxy and Server-Side Gateway with a Standalone Node.js Backend.

BFF Architecture — Next.js Proxy and Server-Side Gateway with a Standalone Node.js Backend.

How Should Tokens and Sessions Work?

Opaque Session ID Approach (My Preferred Option)

This is particularly interesting for BFF architecture.

When a user logs in:

  1. The browser sends credentials to Next.js.
  2. Next.js forwards them to the Node.js /auth/login endpoint.
  3. Node.js validates the credentials.
  4. Node.js creates a session record in its database.
  5. Node.js returns an opaque, cryptographically random session identifier to Next.js.
  6. Next.js stores it in an HttpOnly cookie.

This gives you centralized session revocation, device management, and logout capabilities.

The browser does not need direct access to the session identifier through JavaScript because the cookie is HttpOnly.

The downside is that if every request requires a database lookup, you introduce additional latency. That's where caching becomes interesting.

The Latency Problem: How Can We Avoid Extra Authentication Requests?

We can make use of the following strategies:

Single-Pass Auth & Data

The BFF forwards API requests directly to the backend with the session credential attached.

This allows the backend to authenticate and authorize the request as part of the actual API operation and return the requested data in the same round trip, avoiding a separate session-verification request.

Zero Network Overhead at Proxy

proxy.ts performs only a lightweight, local cookie-existence check for faster redirects.

It does not need to communicate with the Node.js backend or query the session database (web app database) on every request.

However, this is only an optimistic check. The actual session still needs to be verified by the backend before granting access to protected data, operations and secured routes.

Per-Request De-Duplication (React.cache)

React.cache can be used to memoize authentication and data-access functions during a React Server Component render pass.

This avoids unnecessary duplicate verification triggered by Server Components or database operations when multiple Server Components require the same session information within the same server request.

It is important to understand that React.cache is not a persistent session cache across separate requests. It has a Single-Render Lifespan and prevents duplicate work during a single render pass.

Throttled Non-Blocking Activity Writes

Session lastActivityAt timestamps in session database are updated asynchronously only after a 5-minute window, preventing unnecessary database writes for each request.

This reduces unnecessary database operations while still maintaining useful session activity information.

With these approaches and architecture, we can maintain a clear separation between the client-facing application, authentication gateway, and actual backend infrastructure while keeping the browser isolated from internal authentication mechanisms and also hiding backend infrastructure URL and API endpoints.