Protecting Routes with Middleware

The Descope Next.js SDK provides authentication middleware to enforce secure access control across application routes. Middleware allows authentication checks before requests reach a page or API, ensuring only authorized users can proceed.

Although the middleware isn't strictly required, it is recommended for consistent and secure route protection.

Note

The Descope Next.js SDK's middleware support requires Next.js 13 or later.

As of Next.js 16, the middleware.ts file convention is deprecated and renamed proxy.ts (same behavior and config/matcher).

middleware.ts still works today, but if you're on Next.js 16+, use proxy.ts instead, or run Next's migration codemod: npx @next/codemod@canary middleware-to-proxy .

This guide covers:

  • Configuring authentication middleware
  • Defining public and private routes
  • Using wildcard paths for flexible route protection
  • Redirecting unauthenticated users
  • Handling session expiration and forced re-authentication

Setting Up Authentication Middleware

In Next.js, middleware intercepts requests before they reach a route. The Descope SDK provides authMiddleware() to enforce authentication for protected pages.

Creating Middleware

Create a middleware.ts file (or proxy.ts, see the note above) in the root of your Next.js project.

middleware.ts
import { authMiddleware } from '@descope/nextjs-sdk/server';

export default authMiddleware({
  projectId: process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID,
  redirectUrl: '/sign-in',
  publicRoutes: ['/home', '/about'],
  privateRoutes: ['/dashboard', '/profile'],
});

export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

How Middleware and the SDK Works

  • All routes are private by default.
  • Public routes are explicitly defined using publicRoutes.
  • Private routes can be defined using privateRoutes, but if both publicRoutes and privateRoutes are used, privateRoutes is ignored.
  • Middleware redirects unauthenticated users to redirectUrl.
  • By default, a request with an expired session token still passes if its refresh token is valid. You can turn this off with skipRefreshTokenValidation.

How the Middleware Handles a Request

The middleware decides whether a request can continue, but it doesn't pass session data on to your application. For each request, it:

  1. Reads the session token from the Authorization header, or from the DS cookie (or the cookie named in sessionCookieName).
  2. Validates the session token. If the token is missing or invalid, the middleware falls back to validating the refresh token from the DSR cookie (or the cookie named in refreshTokenCookieName), unless skipRefreshTokenValidation is set.
  3. Redirects to redirectUrl if neither token is valid and the route is private.
  4. Forwards the request otherwise, after removing any X-Descope-Session header it arrived with.

The fallback in step 2 is the part of the middleware that skipRefreshTokenValidation controls. When the option is set, the SDK never reads the refresh token cookie:

authMiddleware.ts (excerpt from the Descope Next.js SDK)
const getRefreshJwt = (req: NextRequest, options: MiddlewareOptions) => {
  if (options?.skipRefreshTokenValidation) {
    return undefined;
  }
  return req.cookies?.get(options?.refreshTokenCookieName || 'DSR')?.value;
};

In step 4, the middleware removes the X-Descope-Session header and passes the rest of the request on unchanged:

authMiddleware.ts (excerpt from the Descope Next.js SDK)
const removeSessionHeader = (headers: Headers): Headers => {
  const requestHeaders = new Headers(headers);
  requestHeaders.delete(DESCOPE_SESSION_HEADER);
  return requestHeaders;
};

return NextResponse.next({
  request: { headers: removeSessionHeader(req.headers) },
});

Because the middleware doesn't forward session data, session() and getSession() read the session token from the request and validate it themselves. See User and Session Data for how to use them in Server Components and API routes.

Session Storage Differences Between Next.js and React/JS

By default, the Descope Next.js SDK stores the DS (Descope Session) in a cookie, whereas the Web JS SDK and React SDK store it in localStorage. This means:

  • Next.js SDK (cookies):

    • Accessible via JavaScript.
    • Stored securely in a secure, samesite=lax cookie.
    • Automatically included in server-side requests.
    • Persistent across browser sessions.
  • React SDK (local storage):

    • Accessible via JavaScript.
    • Requires manual handling for secure transmission to the backend.

Note

For more information on configuring the AuthProvider, including options like adjusting the SameSite cookie settings, refer to our Auth Provider documentation

This allows client-side applications to use the token for making authenticated API requests.

Multi-Project SDK Support

Descope's Next.js SDK supports multi-project setups, where each tenant in a multi-tenant application is mapped to a separate Descope project. This approach is ideal when tenants need isolated configurations or dedicated user stores.

A typical setup looks like this:

  • Each request includes a header (e.g., x-tenant-id) that identifies the tenant.
  • The application dynamically initializes the Descope SDK using the project ID associated with the tenant.
  • Middleware handles authentication using the appropriate project.

SDK Instance Caching

To support multi-tenant applications efficiently, the SDK automatically caches instances based on project ID:

  • On the first request for a given project ID, a new SDK instance is created.
  • On subsequent requests with the same project ID, the existing instance is reused.

This per-project caching ensures optimal performance by avoiding redundant SDK initializations while allowing different tenants to use separate Descope configurations.

Note

Per-project configuration extends to Next.js SDK functions like session(). When assigning a separate project to each tenant, the SDK automatically inherits the appropriate project settings, ensuring consistent authentication across your application.

Example: Tenant-Based Authentication

Here's a complete example showing how to implement tenant-based authentication in your middleware:

import { authMiddleware } from '@descope/nextjs-sdk/server';
import { NextRequest } from 'next/server';

type TenantConfig = { projectId: string; baseUrl?: string };

// Tenant configuration mapping
const tenantConfigs: Record<string, TenantConfig> = {
  'tenant-a': {
    projectId: 'tenant-a-project',
    baseUrl: '__BaseURL__',
  },
  'tenant-b': {
    projectId: 'tenant-b-project', 
    baseUrl: '__BaseURL__',
  },
};

export const middleware = async (request: NextRequest) => {
  const tenantId = request.headers.get('x-tenant-id');
  
  if (!tenantId || !tenantConfigs[tenantId]) {
    return new Response('Invalid tenant', { status: 400 });
  }

  const config = tenantConfigs[tenantId];
  
  const auth = authMiddleware({
    projectId: config.projectId,
    baseUrl: config.baseUrl,
    redirectUrl: '/sign-in',
    privateRoutes: ['/dashboard', '/profile'],
    publicRoutes: ['/home', '/about'],
  });

  return await auth(request);
};

export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

Using Wildcard Paths for Route Protection

Wildcard paths (*) simplify route protection by applying authentication requirements to entire sections of an application.

Protecting API Endpoints

export default authMiddleware({
  privateRoutes: ['/api/*'],
});

Protecting an Admin Section

export default authMiddleware({
  privateRoutes: ['/admin/*'],
});

Redirecting Unauthenticated Users

By default, unauthenticated users are redirected to /sign-in. To customize this behavior, update redirectUrl.

Redirecting to a Custom Login Page

export default authMiddleware({
  redirectUrl: '/auth/login',
});

Requiring a Valid Session Token

By default, the middleware treats a valid refresh token as enough to let a request through, even when the session token is missing or expired. That keeps users from being sent to sign-in every time their short-lived session token expires.

The middleware only validates the refresh token, though. It doesn't use the refresh token to issue a new session token. A request that passes on the refresh token alone therefore reaches your server code without a valid session token, and session() returns undefined for it. If your Server Components or API routes rely on session() for every private route, that gap shows up as signed-in users who appear to have no session.

To close it, set skipRefreshTokenValidation to true. The middleware then never reads the refresh token cookie, and any request to a private route without a valid session token is redirected to redirectUrl.

Note

skipRefreshTokenValidation is available in @descope/nextjs-sdk version 0.16.0 and later.

middleware.ts
import { authMiddleware } from '@descope/nextjs-sdk/server';

export default authMiddleware({
  projectId: process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID,
  redirectUrl: '/sign-in',
  skipRefreshTokenValidation: true,
});

export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

If you store the refresh token in a cookie with a custom name, set refreshTokenCookieName so the default fallback reads the right cookie. It has no effect when skipRefreshTokenValidation is true.

What Your App Needs to Handle

With this option on, a user whose session token has expired but whose refresh token is still valid is redirected to your sign-in route. They don't have to sign in again, because on the client the AuthProvider refreshes the session token from the refresh token on its own (autoRefresh is on by default).

Two things follow from that:

  • Your sign-in page needs to send authenticated users on. Otherwise a user whose session was just refreshed stays on the sign-in page. Rendering the Descope component with redirectAfterSuccess handles this, as does checking useSession() and redirecting yourself.
  • The redirect doesn't keep the original path. The middleware replaces the path with redirectUrl and only carries over the query parameters. If you want to return users to the page they started on, you need to save that path yourself before redirecting.

Controlling Log Levels in the Descope Next.js SDK

The Descope Next.js SDK allows you to control logging levels for debugging and monitoring authentication-related events. This is useful for diagnosing issues during development and ensuring secure authentication flows in production.

Supported Log Levels

The logLevel option in authMiddleware() can be set to one of the following values:

Log LevelDescription
debugLogs detailed debug messages, useful for troubleshooting authentication flows.
infoLogs general informational messages, such as successful logins and token validations.
warnLogs warnings about potential misconfigurations or non-critical issues.
errorLogs only critical authentication failures and errors.

Configuring Log Levels

You can set the log level when defining your middleware:

import { authMiddleware } from '@descope/nextjs-sdk/server';

export default authMiddleware({
  projectId: process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID,
  logLevel: 'debug', // Change to 'info', 'warn', or 'error' as needed
  redirectUrl: '/sign-in',
});

Example: Debugging Authentication

Setting the log level to debug provides detailed output in the console, helping to trace authentication issues.

import { authMiddleware } from '@descope/nextjs-sdk/server';

export default authMiddleware({
  projectId: process.env.NEXT_PUBLIC_DESCOPE_PROJECT_ID,
  logLevel: 'debug', // Enables verbose debugging logs
  redirectUrl: '/sign-in',
});

Sample Debug Logs

When logLevel: 'debug' is set, you might see logs like:

Auth middleware starts
Auth middleware finishes

If an error occurs:

Auth middleware starts
Failed to validate JWT: Failed to validate JWT  [JWSInvalid: Compact JWS must be a string or Uint8Array] {
    code: 'ERR_JWS_INVALID',
    name: 'JWSInvalid'
}
Redirecting to /sign-in
  • Development: Use debug or info to get detailed logs while debugging authentication.
  • Production: Use warn or error to log only critical authentication failures.

For full implementation details, check the sample projects:

Was this helpful?

On this page