Created
August 21, 2024 14:50
-
-
Save ErfanEbrahimnia/534af2ebe1217c2d7def7eb7486855e2 to your computer and use it in GitHub Desktop.
Simple Basic Auth password protection for Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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