Beginner Tech Blog

Beginner Tech Blog Branding

Next.js 15 BASIC認証

2025/02/03 14:50

リリース前のため、本番環境に取り急ぎのBASIC認証。
使い捨てのためID/PW直書き(よくない)
実際に正式に何かで利用する場合は.envに書き直す。

middleware.ts

import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  const basicAuth = req.headers.get('authorization');
  const url = req.nextUrl;

  if (process.env.NODE_ENV === 'production') {
    if (basicAuth) {
      const authValue = basicAuth.split(' ')[1];
      const [user, pwd] = atob(authValue).split(':');

      if (user === 'hoge' && pwd === 'hoge') {
        return NextResponse.next();
      }
    }
    url.pathname = '/api/auth';

    return NextResponse.rewrite(url);
  }
}

api/auth/route.ts

import { NextResponse } from 'next/server';
import { headers } from 'next/headers';

export async function GET() {
  return new NextResponse('Auth Required.', {
    status: 401,
    headers: {
      'WWW-Authenticate': 'Basic realm="Secure Area"'
    },
  });
}