Created
June 23, 2022 20:27
-
-
Save jordanmaslyn/eb80b97ddbc8966bf119f47ac811e278 to your computer and use it in GitHub Desktop.
Force Basic Auth for your Next.JS site
This file contains hidden or 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 { 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"', | |
}, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo for GA version of middleware available at: https://github.com/jordanmaslyn/middleware-basic-auth-demo