{"id":16863,"library":"nextjs-basic-auth-middleware","title":"Next.js Basic Auth Middleware","description":"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.","status":"active","version":"3.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/labd/nextjs-basic-auth-middleware","tags":["javascript","typescript"],"install":[{"cmd":"npm install nextjs-basic-auth-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add nextjs-basic-auth-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add nextjs-basic-auth-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for Next.js Middleware functionality.","package":"next","optional":false}],"imports":[{"note":"This package, like Next.js Middleware itself, is ESM-first. Use `import` syntax. CommonJS `require` will likely lead to errors.","wrong":"const createNextAuthMiddleware = require('nextjs-basic-auth-middleware').createNextAuthMiddleware;","symbol":"createNextAuthMiddleware","correct":"import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware';"},{"note":"Use this named import for integrating basic auth checks within a larger, custom Next.js middleware function.","wrong":"const nextBasicAuthMiddleware = require('nextjs-basic-auth-middleware').nextBasicAuthMiddleware;","symbol":"nextBasicAuthMiddleware","correct":"import { nextBasicAuthMiddleware } from 'nextjs-basic-auth-middleware';"},{"note":"When using TypeScript, import `AuthOptions` to type the configuration object passed to the middleware functions.","symbol":"AuthOptions","correct":"import type { AuthOptions } from 'nextjs-basic-auth-middleware';"}],"quickstart":{"code":"import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware';\nimport type { NextRequest } from 'next/server';\n\n// Define your basic authentication credentials.\n// In a real application, fetch these securely from environment variables or a secret management service.\n// Example using environment variables for overriding:\n// BASIC_AUTH_CREDENTIALS=myuser:mypassword|admin:adminpass\nconst users = [\n  { name: 'testuser', password: 'testpassword' },\n  { name: 'another', password: 'secretpassword' }\n];\n\nconst authOptions = {\n  users: users,\n  realm: 'Restricted Area',\n  message: 'Authentication Required - Please provide valid credentials.'\n};\n\nexport const middleware = createNextAuthMiddleware(authOptions);\n\nexport const config = {\n  // Matcher to apply basic auth to all routes.\n  // Adjust this regex to secure specific paths, e.g., ['/admin/:path*']\n  matcher: ['/(.*)']\n};","lang":"typescript","description":"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."},"warnings":[{"fix":"Remove any usage of `createApiPage`. The `createNextAuthMiddleware` function now handles the 401 response internally using `NextResponse`.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=2.0.0 <3.0.0"},{"fix":"Upgrade to `nextjs-basic-auth-middleware@^3.1.1` or the latest stable version to incorporate these critical fixes.","message":"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.","severity":"gotcha","affected_versions":"<3.1.1"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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`.","cause":"Attempting to use `createApiPage` after upgrading to version 3.x.","error":"TypeError: (0 , nextjs_basic_auth_middleware__WEBPACK_IMPORTED_MODULE_0__.createApiPage) is not a function"},{"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.","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.","error":"Error: The edge runtime does not support Node.js 'http' module."},{"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.","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.","error":"Internal Server Error (500) when providing a malformed Authorization header."},{"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.","cause":"Older versions of the `parseCredentials` logic incorrectly split credentials on every colon, failing to parse passwords containing the character.","error":"Basic authentication fails when passwords contain a colon ':' character."}],"ecosystem":"npm","meta_description":null}