Next.js Basic Auth Middleware

3.1.1 · active · verified Wed Apr 22

nextjs-basic-auth-middleware provides basic authentication support for Next.js applications by leveraging the official Middleware API. This library simplifies the process of securing routes, allowing developers to define credentials directly in code or override them via environment variables like `BASIC_AUTH_CREDENTIALS`. The current stable version is 3.1.1, which includes important security and correctness fixes. Releases are typically driven by Next.js version compatibility or critical bug fixes. Key differentiators include its tight integration with Next.js's native middleware, support for multiple user credentials, and its ability to deliver a standard 401 Unauthorized response directly from the middleware layer without relying on API pages, a significant improvement introduced in v3. It offers a cleaner and less hacky approach compared to previous methods, ensuring proper HTTP status codes for browsers and clients.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to implement basic authentication across all routes in a Next.js application using `createNextAuthMiddleware`. It shows how to define users directly and configures the middleware with a custom realm and message. The `config.matcher` is set to protect all routes.

import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware';
import type { NextRequest } from 'next/server';

// Define your basic authentication credentials.
// In a real application, fetch these securely from environment variables or a secret management service.
// Example using environment variables for overriding:
// BASIC_AUTH_CREDENTIALS=myuser:mypassword|admin:adminpass
const users = [
  { name: 'testuser', password: 'testpassword' },
  { name: 'another', password: 'secretpassword' }
];

const authOptions = {
  users: users,
  realm: 'Restricted Area',
  message: 'Authentication Required - Please provide valid credentials.'
};

export const middleware = createNextAuthMiddleware(authOptions);

export const config = {
  // Matcher to apply basic auth to all routes.
  // Adjust this regex to secure specific paths, e.g., ['/admin/:path*']
  matcher: ['/(.*)']
};

view raw JSON →