Add Auth Middleware

Configure auth middleware to protect your Session Endpoint and any future routes requiring authentication.

To protect your Session Endpoint and other future API routes, you'll need to use the createAuthMiddleware() function to create an auth middleware instance. Then, you'll use the created middleware within the Next.js proxy/middleware.

Configure Auth Middleware

Create and configure the authentication middleware in your src/wristband.ts file.

// src/wristband.ts

import * as http from 'http';
import { createWristbandAuth, getSessionFromRequest, SessionOptions } from '@wristband/nextjs-auth';

export const wristbandAuth = createWristbandAuth({
  clientId: '<WRISTBAND_CLIENT_ID>',
  clientSecret: '<WRISTBAND_CLIENT_SECRET>',
  wristbandApplicationVanityDomain: '<WRISTBAND_APPLICATION_VANITY_DOMAIN>',
});

const sessionOptions: SessionOptions = {
  secrets: '<your-generated-secret>'
};

export function getRequestSession(request: NextRequest) {
  return getSessionFromRequest(request, sessionOptions);
}

/*
 * NEW: Configure auth middleware to require authenticated sessions with our configured options.
 */
export const requireAuth = wristbandAuth.createMiddlewareAuth({
  authStrategies: ['SESSION'],
  sessionConfig: {
    sessionOptions,
    sessionEndpoint: '/api/auth/session'  // This is the default value if none is provided.
  },
});

Use Auth Middleware

Depending on the version of Next.js you are using, you'll need to create a proxy/middleware file:

  • Next.js 16+: Create the proxy file at src/proxy.ts
  • Next.js 15 and earlier: Create the middleware file at src/middleware.ts

After you've created the file, use your auth middleware instance:

// src/proxy.ts

import { NextRequest } from 'next/server';
import { requireAuth } from 'src/wristband';

export async function proxy(request: NextRequest) {
  return await requireAuth(request);
}

export const config = {
  /*
   * Match all paths except for:
   * 1. /_next (Next.js internals)
   * 2. /fonts (inside /public)
   * 3. /examples (inside /public)
   * 4. all root files inside /public (e.g. /favicon.ico)
   */
  matcher: ['/((?!_next|fonts|examples|[\\w-]+\\.\\w+).*)'],
};
// src/middleware.ts

import { NextRequest } from 'next/server';
import { requireAuth } from 'src/wristband';

export async function middleware(request: NextRequest) {
  return await requireAuth(request);
}

export const config = {
  /*
   * Match all paths except for:
   * 1. /_next (Next.js internals)
   * 2. /fonts (inside /public)
   * 3. /examples (inside /public)
   * 4. all root files inside /public (e.g. /favicon.ico)
   */
  matcher: ['/((?!_next|fonts|examples|[\\w-]+\\.\\w+).*)'],
};


What’s Next

Now that your authentication endpoints are set up and configured, let's verify that they're working correctly.