nextjs-basic-auth provides a straightforward method for integrating HTTP Basic Authentication directly into Next.js applications on a per-route basis. Currently at version 0.1.3, this package is designed for simplicity, offering an `initializeBasicAuth` function that returns a check function to be awaited within `getServerSideProps`. It explicitly requires developers to opt out of Next.js's static generation for any authenticated pages, as it needs a server-side context to perform credential checks for each request. Its release cadence appears stable and infrequent, focusing on a specific, well-defined security concern for Next.js page routes. Key differentiators include its direct integration with `getServerSideProps` for page-level protection, in contrast to middleware-based solutions (like `nextjs-basic-auth-middleware`) or more comprehensive authentication libraries (like NextAuth.js) that handle broader authentication flows including sessions, OAuth, and database integration.
npm install nextjs-basic-authVerified import paths — ran on the pinned version, not inferred.
Demonstrates initializing basic authentication with a list of users and applying it to a Next.js page using `getServerSideProps` to protect the route.
For App Router, consider implementing basic auth via Next.js Middleware (e.g., `nextjs-basic-auth-middleware`) or server-side checks within Route Handlers, or using a more comprehensive auth solution like NextAuth.js.
Ensure the protected page explicitly uses `export async function getServerSideProps(ctx) { ... }` (Pages Router) or a server-side rendering strategy (App Router) which prevents static pre-rendering.Utilize environment variables (e.g., `process.env.ADMIN_PASSWORD`) to store passwords for non-development use, or fetch user credentials from a secure backend database or API.
Consider migrating to Next.js Middleware for authentication (e.g., `nextjs-basic-auth-middleware`) or a full-fledged authentication library like NextAuth.js for more robust and maintainable solutions, especially for Next.js versions 12 and above.
Always return an object with a `props` key from `getServerSideProps` after the `basicAuthCheck` has successfully passed, e.g., `return { props: {} };`.Ensure correct 'Authorization: Basic <base64-encoded-credentials>' header is sent with the request, or input correct credentials when prompted by the browser.
Ensure `basicAuthCheck` is only ever called inside `getServerSideProps` (Pages Router) or a similar server-side function/middleware with the `req` and `res` objects correctly destructured from the context (`ctx`).