{"id":16657,"library":"nextjs-basic-auth","title":"Next.js Basic Authentication","description":"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.","status":"maintenance","version":"0.1.3","language":"javascript","source_language":"en","source_url":"https://github.com/jchiatt/nextjs-basic-auth","tags":["javascript","next","nextjs","basic auth","auth","typescript"],"install":[{"cmd":"npm install nextjs-basic-auth","lang":"bash","label":"npm"},{"cmd":"yarn add nextjs-basic-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add nextjs-basic-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for Next.js-specific functions like `getServerSideProps` and handling `req`, `res` objects.","package":"next","optional":false}],"imports":[{"note":"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.","wrong":"const initializeBasicAuth = require('nextjs-basic-auth')","symbol":"initializeBasicAuth","correct":"import initializeBasicAuth from 'nextjs-basic-auth'"}],"quickstart":{"code":"import initializeBasicAuth from 'nextjs-basic-auth';\n\nconst users = [\n  { user: 'user1', password: 'toocool' },\n  { user: 'admin', password: process.env.ADMIN_PASSWORD ?? 'password' }, // Use env vars for production!\n];\n\n// Initialize the basic auth checker once globally or per module\nconst basicAuthCheck = initializeBasicAuth({\n  users: users\n});\n\n// 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)\nexport async function getServerSideProps(ctx) {\n  const { req, res } = ctx;\n\n  // Await the auth check. If authentication fails, it will send a 401 response and prompt the user.\n  await basicAuthCheck(req, res);\n\n  // If authentication passes, proceed with rendering the page\n  return {\n    props: {},\n  };\n}\n\n// If using the App Router, this pattern is less direct and would typically involve server components or middleware.\n// This example is primarily for the Pages Router where getServerSideProps is common.","lang":"javascript","description":"Demonstrates initializing basic authentication with a list of users and applying it to a Next.js page using `getServerSideProps` to protect the route."},"warnings":[{"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.","message":"This 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.","severity":"breaking","affected_versions":">=0.1.0"},{"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.","message":"Protecting 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.","severity":"gotcha","affected_versions":">=0.1.0"},{"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.","message":"Storing 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.","severity":"gotcha","affected_versions":">=0.1.0"},{"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.","message":"The 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.","severity":"deprecated","affected_versions":">=0.1.0"}],"env_vars":null,"search_vec":"'0.1.3':30 'appear':85 'applic':20 'auth':7,126,150,151 'authent':3,16,65,131,138 'await':48 'base':120 'basi':26 'basic':2,6,15,125,149 'broader':137 'cadenc':84 'check':44,78 'comprehens':130 'concern':97 'context':74 'contrast':116 'credenti':77 'current':27 'databas':144 'defin':95 'design':34 'develop':54 'differenti':103 'direct':17,106 'explicit':52 'flow':139 'focus':89 'function':40,45 'generat':62 'getserversideprop':50,109 'handl':136 'http':14 'includ':104,140 'infrequ':88 'initializebasicauth':39 'integr':13,107,145 'javascript':146 'key':102 'level':113 'librari':132 'like':122,133 'method':11 'middlewar':119,127 'middleware-bas':118 'need':69 'next':147 'next.js':1,19,59,99 'nextauth.js':134 'nextj':5,124,148 'nextjs-basic-auth':4 'nextjs-basic-auth-middlewar':123 'oauth':142 'offer':37 'opt':56 'packag':32 'page':66,100,112 'page-level':111 'per':24 'per-rout':23 'perform':76 'protect':114 'provid':8 'releas':83 'request':81 'requir':53 'return':42 'rout':25,101 'secur':96 'server':72 'server-sid':71 'session':141 'side':73 'simplic':36 'solut':121 'specif':92 'stabl':86 'static':61 'straightforward':10 'typescript':152 'version':29 'well':94 'well-defin':93 'within':49","created_at":"2026-04-22T05:18:22.264819+00:00","updated_at":"2026-04-22T05:18:22.264819+00:00","problems":[{"fix":"Always return an object with a `props` key from `getServerSideProps` after the `basicAuthCheck` has successfully passed, e.g., `return { props: {} };`.","cause":"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.","error":"Error: API resolved without sending a response for /protected, this may result in stalled requests."},{"fix":"Ensure correct 'Authorization: Basic <base64-encoded-credentials>' header is sent with the request, or input correct credentials when prompted by the browser.","cause":"This is the expected response when basic authentication fails, either due to incorrect username/password or missing credentials in the request header.","error":"401 Unauthorized"},{"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`).","cause":"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.","error":"TypeError: Cannot read property 'url' of undefined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/jchiatt/nextjs-basic-auth","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/nextjs-basic-auth","openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","auth-security"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-21","install_tag":null}}