🦔

Next.jsにAuth0 v4の導入

2025/02/14に公開

Next.jsにAuth0 v4の導入

  • 最近、@auth0/nextjs-auth0のv4正式版4.0.1が出てきました、それについてNext.jsにAuth0 v4の導入方法を紹介します。

設定

  • パッケージ @auth0/nextjs-auth0

  • Auth0のDashboardの設定 (開発環境)

    • Applicationのところに一つのApplicationを作る
    • Application URIsのところに
      • Allowed Callback URLshttp://localhost:3000/auth/callback にする
      • Allowed Callback URLshttp://localhost:3000, http://localhost:3000/auth/logout にする
    • Domain, Client ID, Client Secretを取得して、Next.jsのプロジェクトの.envの環境変数を設定する
  • Next.jsのプロジェクトの.envの設定

AUTH0_DOMAIN=[Dashboardからの値]
AUTH0_CLIENT_ID=[Dashboardからの値]
AUTH0_CLIENT_SECRET=[Dashboardからの値]
AUTH0_SECRET=[openssl rand -hex 32 で生成できる]
APP_BASE_URL=http://localhost:3000
NEXT_PUBLIC_APP_LOGOUT_URL=http://localhost:3000/auth/logout
NEXT_PUBLIC_APP_CLIENT_ID=[{AUTH0_CLIENT_ID}]
NEXT_PUBLIC_APP_AUTH0_V2_LOGOUT_URL=https://{AUTH0_DOMAIN}/v2/logout

プログラミング

  • 画面、routeをアクセスの時、ログインの状態であるかどうかを確保するため、middleware.tsを作る
import type { NextRequest } from "next/server";

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

export async function middleware(request: NextRequest) {
  return await auth0.middleware(request);
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};
  • ログイン後のcallback: lib/auth0.ts

    • onCallbackの中に、ログインの後にやりたいことをできる、例:他のURLにredirectする
    import { Auth0Client } from "@auth0/nextjs-auth0/server";
    import { NextResponse } from "next/server";
    
    export const auth0 = new Auth0Client({
      session: {
        rolling: true,
        absoluteDuration: 60 * 60 * 24 * 7, // 7 days in seconds
        inactivityDuration: 60 * 60 * 24 * 3, // 3 days in seconds
      },
    
      async onCallback(error, context, session) {
        // redirect the user to a custom error page
        if (error || !session?.user) {
          return NextResponse.redirect(
            new URL(
              `/error?error=${error?.message || "unknown error"}`,
              process.env.APP_BASE_URL,
            ),
          );
        }
    
        // 他のカスタマイズログインロジック
    
        // complete the redirect to the provided returnTo URL
        return NextResponse.redirect(
          new URL(context.returnTo || "/", process.env.APP_BASE_URL),
        );
      },
    });
    
    • onCallback以外の他の関数も設定できます、活用して、ログインのロジックをカスタマイズできる
  • ログインの設定

    • リンク:/auth/login
      • <a href="/auth/login">Log in</a>
      • redirect("/auth/login");
  • Auth0ログアウトの設定, v2 logoutリンク: https://{AUTH0_DOMAIN}/v2/logout

<button>
  <a
    href={`${process.env.NEXT_PUBLIC_APP_AUTH0_V2_LOGOUT_URL}?client_id=${encodeURIComponent(
      process.env.NEXT_PUBLIC_APP_CLIENT_ID!,
      )}&returnTo=${encodeURIComponent(
      process.env.NEXT_PUBLIC_APP_LOGOUT_URL!,
      )}`}
    >
    <div className="flex flex-row w-full items-center">
      <LogOut className="mr-2 h-4 w-4" />
      <span className="text-xs">ログアウト</span>
    </div>
  </a>
</button>
  • ログインのユーザ情報をアクセスする
    • Server component / route
      • (await auth0.getSession())?.user
    • Client component
      • useUser() hook
Bizlink Developers Blog

Discussion