Skip to content

Instantly share code, notes, and snippets.

@kuc-arc-f
Last active August 12, 2022 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuc-arc-f/459e28df0d4e87396dbf94133a41a458 to your computer and use it in GitHub Desktop.
Save kuc-arc-f/459e28df0d4e87396dbf94133a41a458 to your computer and use it in GitHub Desktop.
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