Blog>
Snippets

Middleware Authentication

Implement middleware in a Next.js 14 project to authenticate requests before they reach server actions.
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.headers.get('Authorization')?.replace('Bearer ', '');

  // Verify token logic (mock implementation)
  const verifyToken = (token) => token === 'valid-token';

  if (!token || !verifyToken(token)) {
    // Token not present or not valid; return a 401 Unauthorized response
    return new Response('Unauthorized', { status: 401 });
  }

  // If the token is valid, return NextResponse.next() to continue
  return NextResponse.next();
}
This code represents a Next.js middleware function that checks for a valid Authorization token in the request headers. It uses the 'next/server' package to handle the response. If the token is missing or invalid, it returns a 401 Unauthorized response. Otherwise, the function allows the request to proceed to the next middleware or the server action.