Nest Authbeta

Quickstart — Next.js

A minimal Next.js (App Router) app with SSR auth.

Authenticated server components and route handlers, on top of the backend quickstart.

1. Set up

pnpm create next-app@latest --typescript --app --no-tailwind myapp
cd myapp
pnpm add @ackplus/nest-auth-react @ackplus/nest-auth-client

2. The auth helpers

// lib/auth.ts
import { AuthClient } from '@ackplus/nest-auth-client';
import { createNextAuthHelpers } from '@ackplus/nest-auth-react';
 
export const client = new AuthClient({
  baseUrl: process.env.NEXT_PUBLIC_API_URL!,
  accessTokenType: 'cookie',
});
 
export const authHelpers = createNextAuthHelpers({
  baseUrl: process.env.NEXT_PUBLIC_API_URL!,
});

accessTokenType: 'cookie' means the backend sets HttpOnly cookies that Next.js can read server-side.

3. The root layout

// app/layout.tsx
import { cookies } from 'next/headers';
import { NextAuthProvider } from '@ackplus/nest-auth-react';
import { client, authHelpers } from '@/lib/auth';
 
export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const initialState = await authHelpers.getServerAuth(await cookies());
 
  return (
    <html lang="en">
      <body>
        <NextAuthProvider client={client} initialState={initialState}>
          {children}
        </NextAuthProvider>
      </body>
    </html>
  );
}

getServerAuth reads cookies, calls /auth/verify-session, and gives you a hydration-ready snapshot. The first render is fully authenticated.

4. A protected server component

// app/dashboard/page.tsx
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { authHelpers } from '@/lib/auth';
 
export default async function DashboardPage() {
  const auth = await authHelpers.getServerAuth(await cookies());
  if (!auth.isAuthenticated) redirect('/login');
 
  return <h1>Welcome {auth.user?.email}</h1>;
}

5. A protected API route

// app/api/private/route.ts
import { authHelpers } from '@/lib/auth';
 
export const GET = authHelpers.withAuth(async (req) => {
  return Response.json({ user: req.auth.user });
});

6. Middleware redirects

// middleware.ts
import { NextResponse, type NextRequest } from 'next/server';
 
const PROTECTED = ['/dashboard', '/account'];
 
export function middleware(req: NextRequest) {
  if (!PROTECTED.some((p) => req.nextUrl.pathname.startsWith(p))) {
    return NextResponse.next();
  }
  if (!req.cookies.get('accessToken')) {
    const url = req.nextUrl.clone();
    url.pathname = '/login';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

7. Login page

Same <LoginPage> from the React quickstartuseNestAuth().login(...) works identically.

8. Run it

pnpm dev

Open http://localhost:3000/dashboard, get redirected, sign in, get redirected back.

What's next

On this page