Next.js Basic Auth Middleware
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
-
TypeError: (0 , nextjs_basic_auth_middleware__WEBPACK_IMPORTED_MODULE_0__.createApiPage) is not a function
cause Attempting to use `createApiPage` after upgrading to version 3.x.fixThe `createApiPage` function was removed in v3.0.0. Remove all calls to `createApiPage` as the 401 response is now handled internally by `createNextAuthMiddleware`. -
Error: The edge runtime does not support Node.js 'http' module.
cause Using an older version of the middleware that relied on Node.js APIs within the Edge Runtime, or an incorrect `config.matcher` that applies the middleware to incompatible environments.fixEnsure you are using `nextjs-basic-auth-middleware` v3.x with Next.js >=13.1. This version is designed for the Edge Runtime. Verify your `config.matcher` to ensure it only applies to routes where middleware is intended to run. -
Internal Server Error (500) when providing a malformed Authorization header.
cause Previous versions of the middleware could throw an unhandled exception when processing invalid or malformed basic auth headers, resulting in a 500 server error instead of a graceful 401.fixUpgrade to `nextjs-basic-auth-middleware@^3.1.1` to fix this issue. This version correctly catches exceptions and returns a 401 status code. -
Basic authentication fails when passwords contain a colon ':' character.
cause Older versions of the `parseCredentials` logic incorrectly split credentials on every colon, failing to parse passwords containing the character.fixUpgrade to `nextjs-basic-auth-middleware@^3.1.1`. The updated `parseCredentials` function now correctly splits only on the *first* colon, allowing colons in passwords.
Warnings
- breaking Version 3.0.0 removed the `createApiPage` export and changed the 401 response mechanism. It now uses Middleware responses directly instead of redirecting to an API page. This is a cleaner approach but requires adapting existing v2 implementations.
- breaking Version 3.0.0 introduced a breaking change by requiring Next.js version 13.1 or higher due to its reliance on newer Middleware response capabilities. Previous versions of Next.js are not supported with v3.x of this package.
- breaking Version 2.0.0 contained breaking changes by removing 'SSR Middleware' functionality and updating the Next.js middleware implementation to use API pages for 401 error messages. This was superseded by v3.0.0's changes.
- gotcha Version 3.1.1 fixed several security and correctness issues, including catching exceptions from malformed authorization headers (preventing 500s), allowing colons in passwords, and eliminating a timing leak in credential comparison. Older versions may be vulnerable to these issues.
- gotcha When integrating `nextBasicAuthMiddleware` into a custom middleware chain, be aware that if authentication fails, the middleware will immediately return a 401 response and stop processing any subsequent middleware functions. Place it strategically.
Install
-
npm install nextjs-basic-auth-middleware -
yarn add nextjs-basic-auth-middleware -
pnpm add nextjs-basic-auth-middleware
Imports
- createNextAuthMiddleware
const createNextAuthMiddleware = require('nextjs-basic-auth-middleware').createNextAuthMiddleware;import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware'; - nextBasicAuthMiddleware
const nextBasicAuthMiddleware = require('nextjs-basic-auth-middleware').nextBasicAuthMiddleware;import { nextBasicAuthMiddleware } from 'nextjs-basic-auth-middleware'; - AuthOptions
import type { AuthOptions } from 'nextjs-basic-auth-middleware';
Quickstart
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: ['/(.*)']
};