Next.js
Add authentication to your Next.js app with Clowk
Install
pnpm add @clowk/nextjsSet your keys
NEXT_PUBLIC_CLOWK_PUBLISHABLE_KEY=pk_live_...
CLOWK_SECRET_KEY=sk_live_...Add middleware
Create a middleware file to protect routes:
import { clowkMiddleware } from '@clowk/nextjs'
export default clowkMiddleware({
secretKey: process.env.CLOWK_SECRET_KEY,
publicRoutes: ['/', '/sign-in', '/sign-up'],
signInUrl: '/sign-in',
})
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}Server Components
Access the authenticated user in Server Components:
import { auth } from '@clowk/nextjs'
import { redirect } from 'next/navigation'
export default async function Dashboard() {
const { user, signedIn } = await auth({
secretKey: process.env.CLOWK_SECRET_KEY,
})
if (!signedIn) redirect('/sign-in')
return (
<div>
<h1>Hello, {user?.name}</h1>
<p>{user?.email}</p>
</div>
)
}Route Handlers
import { auth } from '@clowk/nextjs'
import { NextResponse } from 'next/server'
export async function GET() {
const { user, signedIn } = await auth({
secretKey: process.env.CLOWK_SECRET_KEY,
})
if (!signedIn) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
return NextResponse.json({ user })
}Client Components
@clowk/nextjs re-exports all @clowk/react components and hooks:
'use client'
import { SignInButton, SignOutButton, useAuth } from '@clowk/nextjs'
export function Header() {
const { signedIn, user } = useAuth()
if (!signedIn) return <SignInButton />
return (
<div>
<span>{user?.name}</span>
<SignOutButton />
</div>
)
}Next steps
- React quickstart — client-side only setup
- Full Next.js integration — complete API reference