Skip to content

Instantly share code, notes, and snippets.

@kuc-arc-f
Last active Aug 12, 2022
Embed
What would you like to do?
Next.js 12 で、Basic認証
NEXT_PUBLIC_USER=hoge
NEXT_PUBLIC_PASS=fuga
// 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