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-middlewareVerified import paths — ran on the pinned version, not inferred.
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.
Remove any usage of `createApiPage`. The `createNextAuthMiddleware` function now handles the 401 response internally using `NextResponse`.
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.
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.
Upgrade to `nextjs-basic-auth-middleware@^3.1.1` or the latest stable version to incorporate these critical fixes.
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.
The `createApiPage` function was removed in v3.0.0. Remove all calls to `createApiPage` as the 401 response is now handled internally by `createNextAuthMiddleware`.
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.
Upgrade to `nextjs-basic-auth-middleware@^3.1.1` to fix this issue. This version correctly catches exceptions and returns a 401 status code.
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.