Skip to content

Instantly share code, notes, and snippets.

@ErfanEbrahimnia
Created August 21, 2024 14:50
Show Gist options
  • Save ErfanEbrahimnia/534af2ebe1217c2d7def7eb7486855e2 to your computer and use it in GitHub Desktop.
Save ErfanEbrahimnia/534af2ebe1217c2d7def7eb7486855e2 to your computer and use it in GitHub Desktop.
Simple Basic Auth password protection for Next.js
import { type NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) {
return basicAuth(request);
}
function basicAuth(request: NextRequest) {
const authHeader = request.headers.get("Authorization");
const validCredentials = process.env.BASIC_AUTH_CREDENTIALS; // e.g. admin:12345
if (!authHeader) {
return createUnauthorizedResponse();
}
const [authType, base64Credentials] = authHeader.split(" ");
if (authType !== "Basic" || !base64Credentials) {
return createUnauthorizedResponse();
}
const credentials = Buffer.from(base64Credentials, "base64").toString();
if (credentials !== validCredentials) {
return createUnauthorizedResponse();
}
return NextResponse.next();
}
function createUnauthorizedResponse() {
return new NextResponse("Authentication required", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Access to the site"' },
});
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment