0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js14でBasic認証をかける

Posted at

Next14でBasic認証をかける方法の備忘

結論

"next": "14.2.3",
"react": "^18",
"react-dom": "^18",
ディレクトリ
src/
 |- app/
 |- middleware.js
.env.local
middleware.js
import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: ["/"],
};

export function middleware(req) {
  // 開発時では認証をスキップ
  if (process.env.NODE_ENV === "development") {
    return NextResponse.next();
  }

  // 環境変数が設定されていない場合は認証をスキップ
  if (!process.env.BASIC_AUTH_PASSWORD) {
    return NextResponse.next();
  }

  const basicAuth = req.headers.get("authorization");

  if (basicAuth) {
    const authValue = basicAuth.split(" ")[1] ?? "";
    const [user, pwd] = atob(authValue).split(":");

    if (
      user === process.env.BASIC_AUTH_USER &&
      pwd === process.env.BASIC_AUTH_PASSWORD
    ) {
      return NextResponse.next();
    }
  }

  return new Response("401 Unauthorized", {
    status: 401,
    headers: {
      "WWW-Authenticate": 'Basic realm="Secure Area"',
    },
  });
}
.env.local
# Basic認証
BASIC_AUTH_USER=username 
BASIC_AUTH_PASSWORD=password

Vercel側での環境変数の設定方法

Vercel側の環境設定
1.png

再デプロイしたらBasic認証が使えるようになった!

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?