Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Created June 23, 2022 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanmaslyn/eb80b97ddbc8966bf119f47ac811e278 to your computer and use it in GitHub Desktop.
Save jordanmaslyn/eb80b97ddbc8966bf119f47ac811e278 to your computer and use it in GitHub Desktop.
Force Basic Auth for your Next.JS site
import { NextRequest, NextResponse } from "next/server";
// eslint-disable-next-line import/prefer-default-export
export function middleware(req: NextRequest) {
const basicAuth = req.headers.get("authorization");
// if the SITE_USERNAME and SITE_PASSWORD env values exist
// then we will require authentication for all requests
if (process.env.SITE_USERNAME && process.env.SITE_PASSWORD) {
if (basicAuth) {
const auth = basicAuth.split(" ")[1];
const [user, pwd] = Buffer.from(auth, "base64").toString().split(":");
if (
user === process.env.SITE_USERNAME &&
pwd === process.env.SITE_PASSWORD
) {
return NextResponse.next();
}
}
return new Response("Auth required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}
}
@jordanmaslyn
Copy link
Author

Demo for GA version of middleware available at: https://github.com/jordanmaslyn/middleware-basic-auth-demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment