-
-
Save kuc-arc-f/459e28df0d4e87396dbf94133a41a458 to your computer and use it in GitHub Desktop.
Next.js 12 で、Basic認証
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
NEXT_PUBLIC_USER=hoge | |
NEXT_PUBLIC_PASS=fuga |
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
// nextjs12_16basic_auth | |
// Next.js 12 で、Basic認証 | |
import { NextRequest, NextResponse } from 'next/server' | |
export const config = { | |
matcher: ['/', '/index'], | |
} | |
export function middleware(req: NextRequest) { | |
const basicAuth = req.headers.get('authorization') | |
const url = req.nextUrl | |
if (basicAuth) { | |
const authValue = basicAuth.split(' ')[1] | |
const [user, pwd] = atob(authValue).split(':') | |
if ( | |
user === process.env.NEXT_PUBLIC_USER && pwd === process.env.NEXT_PUBLIC_PASS | |
) { | |
return NextResponse.next() | |
} | |
} | |
url.pathname = '/api/auth' | |
return NextResponse.rewrite(url) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment