Registry / auth-security / nextjs-basic-auth-middleware

nextjs-basic-auth-middleware

JSON →
library3.1.1jsnpmunverified

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.

npm install nextjs-basic-auth-middleware
INSTALL
IMPORT
SIG · NEXTJS-BASIC-AUTH-
N
nextjs-basic-auth-middleware
auth-securityjavascriptv3.1.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createNextAuthMiddleware
import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware';
const createNextAuthMiddleware = require('nextjs-basic-auth-middleware').createNextAuthMiddleware;
This package, like Next.js Middleware itself, is ESM-first. Use `import` syntax. CommonJS `require` will likely lead to errors.
nextBasicAuthMiddleware
import { nextBasicAuthMiddleware } from 'nextjs-basic-auth-middleware';
const nextBasicAuthMiddleware = require('nextjs-basic-auth-middleware').nextBasicAuthMiddleware;
Use this named import for integrating basic auth checks within a larger, custom Next.js middleware function.
AuthOptions
import type { AuthOptions } from 'nextjs-basic-auth-middleware';
When using TypeScript, import `AuthOptions` to type the configuration object passed to the middleware functions.

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: ['/(.*)'] };
Debug
Known issues
breakingVersion 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.
fix
Remove any usage of `createApiPage`. The `createNextAuthMiddleware` function now handles the 401 response internally using `NextResponse`.
affects: >=3.0.0
breakingVersion 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.
fix
Ensure your project's `next` dependency is `^13.1.0` or higher. For Next.js 12 or 13.0, you must use `nextjs-basic-auth-middleware` version 2.x.
affects: >=3.0.0
breakingVersion 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.
fix
If migrating from v1 to v2, adapt to the API page approach. If migrating to v3 directly, follow v3 instructions and ignore v2's API page mechanism.
affects: >=2.0.0 <3.0.0
gotchaVersion 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.
fix
Upgrade to `nextjs-basic-auth-middleware@^3.1.1` or the latest stable version to incorporate these critical fixes.
affects: <3.1.1
gotchaWhen 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.
fix
Place `nextBasicAuthMiddleware` at the point in your middleware chain where you intend to halt further processing if authentication is not provided or fails, typically after any prerequisite checks.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: (0 , nextjs_basic_auth_middleware__WEBPACK_IMPORTED_MODULE_0__.createApiPage) is not a function
Attempting to use `createApiPage` after upgrading to version 3.x.
fix
The `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.
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.
fix
Ensure 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.
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.
fix
Upgrade 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.
Older versions of the `parseCredentials` logic incorrectly split credentials on every colon, failing to parse passwords containing the character.
fix
Upgrade to `nextjs-basic-auth-middleware@^3.1.1`. The updated `parseCredentials` function now correctly splits only on the *first* colon, allowing colons in passwords.
Upgrade
Version history
3.1.1latest on npm
Audit
Dependencies
nextrequiredRequired for Next.js Middleware functionality.
Agent activity
13 hits · last 30 days
node
12
OpenAI (training)
1
Resources