SDK

Next.js SDK

@authon/nextjsルートミドルウェア、サーバーコンポーネントヘルパー、完全なReact SDKを備えたフルスタックNext.js統合。

npm: @authon/nextjsNext.js 14+App Router

インストール

bash
npm install @authon/nextjs

環境変数

Authon APIキーを .env.local. に追加。Publishable keyはブラウザへの公開が安全ですが、secret keyはサーバーサイドのみに保管してください。

.env.local
NEXT_PUBLIC_AUTHON_PUBLISHABLE_KEY=pk_live_your_publishable_key
AUTHON_SECRET_KEY=sk_live_your_secret_key

レイアウトにAuthonProviderを追加

AuthonProvider をルートレイアウトに追加して、すべてのクライアントコンポーネントが認証コンテキストにアクセスできるようにします。

app/layout.tsx
import type { Metadata } from "next";
import { AuthonProvider } from "@authon/nextjs";

export const metadata: Metadata = {
  title: "My App",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <AuthonProvider
          publishableKey={process.env.NEXT_PUBLIC_AUTHON_PUBLISHABLE_KEY!}
        >
          {children}
        </AuthonProvider>
      </body>
    </html>
  );
}

ミドルウェア

authonMiddleware でエッジでルートを保護。非公開ルートへの未認証リクエストはサインインページに自動リダイレクトされます。

middleware.ts
import { authonMiddleware } from "@authon/nextjs";

export default authonMiddleware({
  // Routes that do NOT require authentication
  publicRoutes: ["/", "/about", "/pricing", "/sign-in", "/sign-up"],

  // Where to redirect unauthenticated users (default: /sign-in)
  signInUrl: "/sign-in",
});

export const config = {
  // Apply middleware to all routes except Next.js internals and static files
  matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\.png$).*)"],
};

サーバーコンポーネント

サーバーコンポーネントとサーバーアクションで @authon/nextjs/server.

auth()

ユーザーIDとトークンゲッターを含むセッションメタデータを返します。軽量 — 完全なユーザーオブジェクトを取得しません。

app/api/orders/route.ts
import { auth } from "@authon/nextjs/server";
import { NextResponse } from "next/server";

export async function GET() {
  const { userId, getToken } = await auth();

  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const token = getToken();
  // Use token to call external APIs on behalf of the user
  const orders = await fetchOrders(userId, token);

  return NextResponse.json({ orders });
}

currentUser()

完全な AuthonUser オブジェクトを取得して返します。サーバーコンポーネントでユーザープロファイルデータが必要な場合に使用。

app/dashboard/page.tsx
import { currentUser } from "@authon/nextjs/server";
import { redirect } from "next/navigation";

export default async function DashboardPage() {
  const user = await currentUser();

  // Redirect if not signed in
  if (!user) {
    redirect("/sign-in");
  }

  return (
    <main>
      <h1>Welcome back, {user.displayName ?? user.email}!</h1>
      <p>Account created: {new Date(user.createdAt).toLocaleDateString()}</p>
      <p>Sign-in count: {user.signInCount}</p>
    </main>
  );
}

クライアントフック & コンポーネント

すべてのReact SDKフックとコンポーネントはクライアントコンポーネントで動作します。 @authon/nextjsからインポート(@authon/reactのすべてを再エクスポート)。

components/Header.tsx
"use client";

import Link from "next/link";
import { SignedIn, SignedOut, UserButton, useAuthon } from "@authon/nextjs";

export function Header() {
  const { openSignIn } = useAuthon();

  return (
    <header className="flex items-center justify-between p-4 border-b">
      <Link href="/">My App</Link>

      <div className="flex items-center gap-3">
        <SignedIn>
          <Link href="/dashboard">Dashboard</Link>
          <UserButton />
        </SignedIn>

        <SignedOut>
          <button onClick={() => openSignIn()} className="btn-primary">
            Sign in
          </button>
        </SignedOut>
      </div>
    </header>
  );
}

APIルートの保護

auth():

app/api/profile/route.ts
import { auth } from "@authon/nextjs/server";
import { currentUser } from "@authon/nextjs/server";
import { NextResponse } from "next/server";

export async function GET() {
  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const user = await currentUser();
  return NextResponse.json({ user });
}

export async function PATCH(request: Request) {
  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  // Update user profile...
  return NextResponse.json({ success: true });
}

サインイン / 登録ページ

埋め込みモーダルコンポーネントで専用サインイン・登録ページを作成:

app/sign-in/page.tsx
import { SignIn } from "@authon/nextjs";

export default function SignInPage() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-slate-950">
      <SignIn mode="embedded" />
    </div>
  );
}
app/sign-up/page.tsx
import { SignUp } from "@authon/nextjs";

export default function SignUpPage() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-slate-950">
      <SignUp mode="embedded" />
    </div>
  );
}
Authon — ユニバーサル認証プラットフォーム