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?

NextJS+Auth0 4系

Posted at

個人開発でNextJS+Auth0触って驚いた

Auth0君って導入めっちゃ優しくて、主要なもの向けにパッケージ公開してくれているんですよね。
えてしてこの手のパッケージはメジャーバージョンで大きく変わるもので、3系と4系で様子が違ってきます。

AIコーディング君でも4系使っているのに3系の実装で書いたりしてくるので、exampleよめって話なんですが……自分が詰まったら記事を書けの精神で書いていきましょう

Auth0clientの作成

import { Auth0Client } from "@auth0/nextjs-auth0/server"

// 環境変数の検証
const requiredEnvVars = {
  AUTH0_SECRET: process.env.AUTH0_SECRET,
  AUTH0_DOMAIN: process.env.AUTH0_DOMAIN,
  AUTH0_CLIENT_ID: process.env.AUTH0_CLIENT_ID,
  AUTH0_CLIENT_SECRET: process.env.AUTH0_CLIENT_SECRET,
  APP_BASE_URL: process.env.APP_BASE_URL,
};

// 必須環境変数が設定されていない場合は警告を表示
const missingVars = Object.entries(requiredEnvVars)
  .filter(([_, value]) => !value)
  .map(([key]) => key);

if (missingVars.length > 0) {
  console.warn(`Missing Auth0 environment variables: ${missingVars.join(', ')}`);
  console.warn('Using default values. Please set proper Auth0 configuration.');
}

export const auth0 = new Auth0Client({
  secret: process.env.AUTH0_SECRET || 'your-auth0-secret-key-here-must-be-at-least-32-characters-long',
  domain: process.env.AUTH0_DOMAIN || 'your-auth0-domain.auth0.com',
  clientId: process.env.AUTH0_CLIENT_ID || 'your-auth0-client-id',
  clientSecret: process.env.AUTH0_CLIENT_SECRET || 'your-auth0-client-secret',
  appBaseUrl: process.env.APP_BASE_URL || 'http://localhost:3000',
});

でミドルウェアの設定、昔はapiを作ってそこにハンドル処理を書かなくてはいけなかったです。

import type { NextRequest } from "next/server"

import { auth0 } from "./lib/auth0"

export async function middleware(request: NextRequest) {
  try {
    return await auth0.middleware(request)
  } catch (error) {
    console.error('Auth0 middleware error:', error)
    return new Response(null, { status: 200 })
  }
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
}

ミドルウェアでの定義になるためパスが変わります。
3系だとapi配下だったため
~/api/auth/callback
だったのですが
~/auth/callback
になります

Auth0側の設定はこうですねー

image.png

以上となります。

締め

AIコーディングで4系指定しているのにも関わらず執拗に3系で書こうとする理由は残念ながら今回は判明しませんでした。いかがでしたか?(クソブログ締め)

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?