Auth0 Next.js SDK

認証Auth0Next.jsTypeScriptReactSSRAPI RoutesOAuth2OpenID ConnectJWT

Auth0 Next.js SDK

概要

Auth0 Next.js SDKは、Next.jsアプリケーションにAuth0の認証機能を統合するための公式ライブラリです。2025年現在、Next.js 15およびReact 19に対応し、サーバーサイドレンダリング(SSR)、静的サイト生成(SSG)、API Routesと完全に統合されています。TypeScriptサポートを提供し、OAuth2、OpenID Connect、JWTトークンによる認証を簡単に実装できます。Auth0の管理画面と連携し、ユーザー管理、ロール管理、セキュリティ設定を一元化できることが特徴です。

特徴

Auth0 Next.js SDKは、Next.jsの特徴を活かした認証機能を提供します。主な特徴として、@auth0/nextjs-auth0パッケージによるNext.js API Routesとの統合、useUserフックによるクライアントサイドでのユーザー状態管理、withPageAuthRequiredによるページレベルでの認証保護を提供します。サーバーサイドレンダリング時の認証状態の保持、セッション管理、CSRF保護などのセキュリティ機能も自動的に処理されます。さらに、Google、Facebook、GitHub、LinkedInなどの外部認証プロバイダーとの統合も簡単に実現できます。

主な機能

  • Next.js完全統合: SSR、SSG、API Routesとの完全な統合
  • TypeScript サポート: 型安全な認証機能の実装
  • 自動セッション管理: 暗号化されたセッションの自動管理
  • API Routes 認証: /api/auth/[...auth0].js による認証エンドポイント
  • React Hooks: useUser フックによるユーザー状態管理
  • ページ保護: withPageAuthRequired による認証保護

使用例

インストールと基本設定

npm install @auth0/nextjs-auth0

環境変数設定

# .env.local
AUTH0_SECRET='your-long-random-secret'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://your-domain.auth0.com'
AUTH0_CLIENT_ID='your-client-id'
AUTH0_CLIENT_SECRET='your-client-secret'

API Routes 設定

// pages/api/auth/[...auth0].ts
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();

App Component設定

// pages/_app.tsx
import type { AppProps } from 'next/app';
import { UserProvider } from '@auth0/nextjs-auth0/client';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

ユーザー情報の取得

// components/Profile.tsx
import { useUser } from '@auth0/nextjs-auth0/client';

export default function Profile() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;
  if (!user) return <div>Not authenticated</div>;

  return (
    <div>
      <h1>Welcome, {user.name}!</h1>
      <p>Email: {user.email}</p>
      <a href="/api/auth/logout">Logout</a>
    </div>
  );
}

ページ保護

// pages/protected.tsx
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
import { GetServerSideProps } from 'next';

export default function Protected() {
  return <div>This page is protected!</div>;
}

export const getServerSideProps: GetServerSideProps = withPageAuthRequired();

API Routes での認証

// pages/api/secure.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0';

export default withApiAuthRequired(async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getSession(req, res);
  const user = session?.user;

  res.status(200).json({ 
    message: 'Secure data', 
    userId: user?.sub 
  });
});

比較・代替手段

優位性

  • Next.jsとの完全な統合と最適化
  • Auth0の包括的な機能と管理画面の活用
  • TypeScriptサポートによる型安全性
  • SSRとSSGでの認証状態の自動処理

注意点

  • Auth0サービスへの依存とコスト
  • インターネット接続が必要
  • Next.js専用の実装

類似ライブラリ比較

  • NextAuth.js: Next.js用のオープンソース認証ライブラリ
  • Auth0 React SDK: React専用の認証ライブラリ
  • Supabase Auth: オープンソースのBaaS認証サービス

学習リソース

公式ドキュメント

チュートリアル

まとめ

Auth0 Next.js SDKは、Next.jsアプリケーションに認証機能を簡単に統合できる強力なライブラリです。Next.jsの特徴を活かしたSSR、SSG、API Routesとの完全な統合により、高いパフォーマンスとセキュリティを実現できます。TypeScriptサポートと豊富なReact Hooksにより、開発者体験も優れています。Auth0サービスの利用料金は発生しますが、開発・運用の効率化と高度なセキュリティ機能を考慮すると、多くのNext.jsプロジェクトで有効な選択肢となります。