Zenn
👮

Next.js 14におけるmiddleware.tsのみでのBASIC認証の掛け方

2025/02/10に公開

はじめに

API Routesを使いたくない。Middlewareのみでどうにかならないかと思ったのでやってみる。

"next": "14.2.16"

実装

.envファイルをルートディレクトリに作成し、BASIC認証のidとパスワードを設定する。

BASIC_ID=id
BASIC_PWD=pwd

ローカル環境にて確認する場合は.env.localなど適宜優先順位を変更してください。

middleware.ts定義

appディレクトリと同一階層にmiddleware.tsを作成し、以下を記載する。

middleware.ts
import { NextRequest, NextResponse } from "next/server";

export default function middleware(req: NextRequest) {
  // basic認証の検証
  const basicAuth = req.headers.get("authorization");
  if (!basicAuth) {
    return new Response("Authentication required", {
      status: 401,
      headers: {
        "WWW-Authenticate": 'Basic realm="Secure Area"',
      },
    });
  }
  try {
    const authValue = basicAuth.split(" ")[1];
    const [user, pwd] = atob(authValue).split(":");
    if (
      !(
        user === process.env.BASIC_ID &&
        pwd === process.env.BASIC_PWD
      )
    ) {
      return new Response("Authentication required", {
        status: 401,
        headers: {
          "WWW-Authenticate": 'Basic realm="Secure Area"',
        },
      });
    }
  } catch (e) {
    return new Response("Invalid Authentication", {
      status: 400,
    });
  }
  return NextResponse.next();
}

実装にあたっての検討事項

API Routesを用いた実装についても検討したが、管理すべきAPIが増えることを回避する、かつ処理を簡略化するためmiddleware.tsに認証の処理をまとめる実装に落ち着いた。
CloudFrontなどアプリケーションの前段がある方はそちらで設定したほうが良いと思う。

終わりに

BASIC認証はシンプルですが、仕組みを知るとためになる。

参考文献

https://zenn.dev/hayato94087/articles/85095219de0e9b
https://nextjs.org/docs/pages/api-reference/edge
https://developer.mozilla.org/ja/docs/Web/HTTP/Authentication

Discussion

ログインするとコメントできます