Registry / web-framework / nextjs-basic-auth

nextjs-basic-auth

JSON →
library0.1.3jsnpmunverified

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-auth
INSTALL
IMPORT
SIG · NEXTJS-BASIC-AUTH
N
nextjs-basic-auth
web-frameworkjavascriptv0.1.3
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.

initializeBasicAuth
import initializeBasicAuth from 'nextjs-basic-auth'
const initializeBasicAuth = require('nextjs-basic-auth')
The package uses ES Modules by default. While Node.js can sometimes interop, explicit ESM import is preferred. CommonJS `require` might lead to issues or incorrect imports depending on project configuration.

Demonstrates initializing basic authentication with a list of users and applying it to a Next.js page using `getServerSideProps` to protect the route.

import initializeBasicAuth from 'nextjs-basic-auth'; const users = [ { user: 'user1', password: 'toocool' }, { user: 'admin', password: process.env.ADMIN_PASSWORD ?? 'password' }, // Use env vars for production! ]; // Initialize the basic auth checker once globally or per module const basicAuthCheck = initializeBasicAuth({ users: users }); // In your Next.js page file (e.g., pages/protected.js or app/protected/page.js for Pages Router or App Router with getServerSideProps emulation) export async function getServerSideProps(ctx) { const { req, res } = ctx; // Await the auth check. If authentication fails, it will send a 401 response and prompt the user. await basicAuthCheck(req, res); // If authentication passes, proceed with rendering the page return { props: {}, }; } // If using the App Router, this pattern is less direct and would typically involve server components or middleware. // This example is primarily for the Pages Router where getServerSideProps is common.
Debug
Known issues
breakingThis package is designed for the Next.js Pages Router and relies on `getServerSideProps`. It does not directly support the new App Router's server components or middleware architecture in the same way. Adapting it for the App Router would require significant manual changes or a different approach.
fix
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.
affects: >=0.1.0
gotchaProtecting a route with `nextjs-basic-auth` requires that the page opts out of Next.js's Static Site Generation (SSG). Pages using this library *must* use `getServerSideProps` or a similar server-side rendering mechanism, as the authentication check needs access to the `req` and `res` objects at runtime.
fix
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.
affects: >=0.1.0
gotchaStoring sensitive credentials like user passwords directly in source code, even if hashed, is a security risk. The `users` array should ideally be populated from secure environment variables or a database, especially for production environments.
fix
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.
affects: >=0.1.0
deprecatedThe package has not seen updates in over 5 years. While it may still function for its specific use case, it does not leverage newer Next.js features like Middleware for authentication, which is generally a more recommended approach for global or group-based route protection in modern Next.js applications.
fix
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.
affects: >=0.1.0
Errors
Common errors & fixes
Error: API resolved without sending a response for /protected, this may result in stalled requests.
The `basicAuthCheck(req, res)` function handles the response for unauthenticated users (sending a 401). If the page's `getServerSideProps` (or equivalent) doesn't explicitly return `props` after a successful authentication, Next.js might warn about an unhandled response.
fix
Always return an object with a `props` key from `getServerSideProps` after the `basicAuthCheck` has successfully passed, e.g., `return { props: {} };`.
401 Unauthorized
This is the expected response when basic authentication fails, either due to incorrect username/password or missing credentials in the request header.
fix
Ensure correct 'Authorization: Basic <base64-encoded-credentials>' header is sent with the request, or input correct credentials when prompted by the browser.
TypeError: Cannot read property 'url' of undefined
This specific error (or similar related to `req` or `res` properties) might occur if `basicAuthCheck` is called outside of a server-side context where `req` and `res` objects are not available, or if incorrect arguments are passed.
fix
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`).
Upgrade
Version history
0.1.3latest on npm
Audit
Dependencies
nextrequiredRequired for Next.js-specific functions like `getServerSideProps` and handling `req`, `res` objects.
Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources