Next.js SDK
@authon/nextjs — Full-stack Next.js integration with route middleware, Server Component helpers, and the complete React SDK.
Installation
npm install @authon/nextjsEnvironment 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.
NEXT_PUBLIC_AUTHON_PUBLISHABLE_KEY=pk_live_your_publishable_key
AUTHON_SECRET_KEY=sk_live_your_secret_keyAuthonProvider in Layout
AddAuthonProvider to your root layout so all Client Components have access to auth context.
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.
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.
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.
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).
"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():
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:
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>
);
}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>
);
}