SDK

Next.js SDK

@authon/nextjsFull-stack Next.js integration with route middleware, Server Component helpers, and the complete React SDK.

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

Installation

bash
npm install @authon/nextjs

Environment Variables

Add your Authon API keys to .env.local. The publishable key is safe to expose to the browser; keep the secret key server-side only.

.env.local
NEXT_PUBLIC_AUTHON_PUBLISHABLE_KEY=pk_live_your_publishable_key
AUTHON_SECRET_KEY=sk_live_your_secret_key

AuthonProvider in Layout

AddAuthonProvider to your root layout so all Client Components have access to auth context.

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>
  );
}

Middleware

UseauthonMiddleware to protect routes at the edge. Unauthenticated requests to non-public routes are automatically redirected to your sign-in page.

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$).*)"],
};

Server Components

Access authentication data in Server Components and Server Actions using the server helpers from @authon/nextjs/server.

auth()

Returns session metadata including the user ID and a token getter. Lightweight — does not fetch the full user object.

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()

Fetches and returns the full AuthonUser object. Use this when you need user profile data in a Server Component.

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>
  );
}

Client Hooks & Components

All React SDK hooks and components work in Client Components. Import from @authon/nextjs(re-exports everything from@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 Route Protection

Protect API routes by checking the session viaauth():

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 });
}

Sign In / Sign Up Pages

Create dedicated sign-in and sign-up pages using the embedded modal components:

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 — Universal Authentication Platform