1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【超簡単】Next.jsでBasic認証を導入してみた

Last updated at Posted at 2022-05-22

はじめに

Next.jsでBasic認証を導入しようと思いましたが、TypeScriptで記載されたサンプルしか見つけられなかったため、JavaScript版を作成しました。

Next.jsでBasic認証を導入する方法

以下をpagesフォルダ配下に作成する

/pages/_middleware.js
import { NextRequest, NextResponse } from 'next/server'

export function middleware(req) {
  const basicAuth = req.headers.get('authorization')

  if (basicAuth) {
    const auth = basicAuth.split(' ')[1]
    const [user, pwd] = Buffer.from(auth, 'base64').toString().split(':')
    if (user === process.env.NEXT_PUBLIC_USER && pwd === process.env.NEXT_PUBLIC_PASS) {
      return NextResponse.next()
    }
  }

  return new Response('Auth required', {
    status: 401,
    headers: {
      'WWW-Authenticate': 'Basic realm="Secure Area"',
    },
  })
}

Buffer.fromでエラーが出た場合は、以下コマンドでbufferを導入する

npm install buffer

ユーザ名やパスワードは環境変数で定義する

.env.local
NEXT_PUBLIC_USER=hoge
NEXT_PUBLIC_PASS=fuga

検証

環境変数を更新したので、サーバを再起動する

npm run dev

npm run devでpackage.jsonに記載のnext devが動作する

package.json
{
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "buffer": "^6.0.3",
    "next": "latest",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  }
}

http://localhost:3000 にアクセスすると、ベーシック認証画面が表示される。
ユーザ名にhoge, パスワードにfugaと入れると認証される。

image.png

キャンセルを押下すると、以下のAuth requiredが表示される。
この文言は_middleware.jsで変更できる

image.png

参考

https://github.com/vercel/examples/tree/main/edge-functions/basic-auth-password
https://tech.012grp.co.jp/entry/2021/11/08/083809
https://stackoverflow.com/questions/70169772/how-to-unprotect-route-in-next-js-middleware

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?