Documentation › Quickstarts

Next.js quickstart

A new Next.js app (App Router, TypeScript) with authto.it sign-in: a home page that shows who is signed in, a protected /account page with the person's claims, and a sign-out that also ends the authto.it session. It uses Auth.js (NextAuth) v4 with authto.it set up as an OpenID Connect provider: PKCE (S256), state and nonce, the code exchanged with your client secret on the server, and the ID token verified against authto.it's keys. Tested with Next.js 16.4.6, next-auth 4.24.15 and Node 24.

1. Create the site

On the authto.it dashboard, open your organization and choose Add site:

NameAnything, for example My Next.js app. People see it on the sign-in page.
Return addresshttp://localhost:3001/api/auth/callback/authto
After sign-out addresshttp://localhost:3001/
TypeServer-side (confidential), so the site gets a client secret.

Copy the client ID and the client secret. The secret is shown once. The site can be invite-only (only the people you add can sign in) or open to anyone with an email address or phone.

An AI tool connected to authto.it's MCP server can create the site for you, but the client secret is only issued on the dashboard.

2. Set up the project

npx create-next-app@latest my-app --ts --app --no-tailwind --no-eslint --no-src-dir --import-alias "@/*" --yes
cd my-app
npm install next-auth@4

Put the settings in .env.local (Next.js keeps it out of git). Make the app secret with openssl rand -base64 32.

.env.local

AUTHTO_ISSUER=https://letme.authto.it
AUTHTO_CLIENT_ID=your-client-id
AUTHTO_CLIENT_SECRET=your-client-secret
NEXTAUTH_URL=http://localhost:3001
NEXTAUTH_SECRET=replace-with-output-of-openssl-rand-base64-32

NEXTAUTH_URL is the app's own address. Auth.js builds the return address from it (/api/auth/callback/authto), and the sign-out below sends people back to it.

3. Add the code

The provider. Auth.js reads authto.it's discovery document, sends PKCE, state and nonce, checks them on the way back, swaps the code using HTTP Basic auth with your secret and verifies the ID token. The person is kept in an encrypted session cookie, along with the ID token for sign-out.

lib/auth.ts

import { connection } from "next/server";
import { getServerSession, type NextAuthOptions } from "next-auth";

export const issuer = process.env.AUTHTO_ISSUER ?? "https://letme.authto.it";

export const authOptions: NextAuthOptions = {
  providers: [
    {
      id: "authto",
      name: "authto.it",
      type: "oauth",
      // Endpoints and signing keys come from discovery.
      wellKnown: `${issuer}/.well-known/openid-configuration`,
      clientId: process.env.AUTHTO_CLIENT_ID,
      clientSecret: process.env.AUTHTO_CLIENT_SECRET,
      client: { token_endpoint_auth_method: "client_secret_basic" },
      authorization: { params: { scope: "openid email profile" } },
      checks: ["pkce", "state", "nonce"],
      // Verify the ID token (signature, iss, aud, exp, nonce) and read
      // the person from it.
      idToken: true,
      profile(claims) {
        return {
          id: claims.sub,
          email: claims.email ?? null,
          name: claims.name ?? null,
          role: claims.role ?? null,
        };
      },
    },
  ],
  pages: { signIn: "/signin" },
  session: { strategy: "jwt" },
  callbacks: {
    // Runs at sign-in with `account` and `profile`, then on every request.
    async jwt({ token, account, profile }) {
      if (account && profile) {
        token.sub = profile.sub; // permanent per site
        token.role = (profile as { role?: string }).role ?? null;
        token.idToken = account.id_token; // kept for sign-out
      }
      return token;
    },
    // What the app sees. The ID token stays on the server.
    async session({ session, token }) {
      session.user = {
        sub: token.sub!,
        email: token.email ?? null,
        name: token.name ?? null,
        role: token.role ?? null,
      };
      return session;
    },
  },
};

// The signed-in person, or null. connection() makes the page render per
// request, since the session cookie differs for every visitor.
export async function getSession() {
  await connection();
  return getServerSession(authOptions);
}

Types for the extra fields (sub, role, the ID token):

types/next-auth.d.ts

import "next-auth";
import "next-auth/jwt";

declare module "next-auth" {
  interface Session {
    user: {
      sub: string;
      email: string | null;
      name: string | null;
      role: string | null;
    };
  }
  interface User {
    role?: string | null;
  }
}

declare module "next-auth/jwt" {
  interface JWT {
    role?: string | null;
    idToken?: string;
  }
}

The Auth.js routes, including the callback at /api/auth/callback/authto:

app/api/auth/[...nextauth]/route.ts

import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

A sign-in page that goes straight to authto.it instead of showing Auth.js's own page:

app/signin/page.tsx

import SignIn from "./sign-in";

export const instant = false;

// Sends the browser straight to authto.it. Signed-out visitors to
// protected pages land here with ?callbackUrl=...
export default async function SignInPage({
  searchParams,
}: {
  searchParams: Promise<{ callbackUrl?: string }>;
}) {
  const { callbackUrl } = await searchParams;
  return <SignIn callbackUrl={callbackUrl ?? "/"} />;
}

app/signin/sign-in.tsx

"use client";

import { useEffect, useRef } from "react";
import { signIn } from "next-auth/react";

export default function SignIn({ callbackUrl }: { callbackUrl: string }) {
  const started = useRef(false);
  useEffect(() => {
    if (started.current) return; // effects run twice in development
    started.current = true;
    signIn("authto", { callbackUrl });
  }, [callbackUrl]);
  return <p>Redirecting to authto.it…</p>;
}

Sign-out. Auth.js's own sign-out only clears the app's cookie, so this route clears it and then sends the browser to authto.it's end_session_endpoint with id_token_hint and post_logout_redirect_uri. authto.it ends its session and returns to the after-sign-out address.

app/signout/route.ts

import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { issuer } from "@/lib/auth";

// Ends the local session, then the authto.it session.
export async function POST(req: NextRequest) {
  const token = await getToken({ req });

  const discovery = await fetch(`${issuer}/.well-known/openid-configuration`, {
    next: { revalidate: 3600 },
  }).then((r) => r.json());

  const url = new URL(discovery.end_session_endpoint);
  if (token?.idToken) url.searchParams.set("id_token_hint", token.idToken);
  url.searchParams.set("client_id", process.env.AUTHTO_CLIENT_ID!);
  url.searchParams.set("post_logout_redirect_uri", `${process.env.NEXTAUTH_URL}/`);

  const res = NextResponse.redirect(url, 303);
  // Delete the session cookie (and its chunks, if it was split).
  for (const { name } of req.cookies.getAll()) {
    if (name.includes("next-auth.session-token")) {
      res.cookies.set(name, "", {
        maxAge: 0,
        path: "/",
        secure: name.startsWith("__Secure-"),
      });
    }
  }
  return res;
}

Protection for /account. In Next.js 16, proxy.ts (formerly middleware.ts) runs before the page and redirects signed-out visitors:

proxy.ts (in the project root, beside app)

import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";

// Signed-out visitors to the pages in `matcher` go to sign-in first.
export async function proxy(req: NextRequest) {
  if (!(await getToken({ req }))) {
    const signin = new URL("/signin", req.url);
    signin.searchParams.set("callbackUrl", req.nextUrl.pathname + req.nextUrl.search);
    return NextResponse.redirect(signin);
  }
}

export const config = { matcher: ["/account/:path*"] };

The pages. Replace the generated home page (you can delete app/page.module.css):

app/page.tsx

import Link from "next/link";
import { getSession } from "@/lib/auth";

// Wait for the session before sending the page.
export const instant = false;

export default async function Home() {
  const session = await getSession();

  if (!session) {
    return (
      <main>
        <p><Link href="/signin">Sign in</Link></p>
      </main>
    );
  }

  return (
    <main>
      <p>Signed in as {session.user.name ?? session.user.email}</p>
      <p><Link href="/account">Account</Link></p>
      <form action="/signout" method="post">
        <button type="submit">Sign out</button>
      </form>
    </main>
  );
}

app/account/page.tsx

import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";

// Wait for the session before sending the page.
export const instant = false;

export default async function Account() {
  const session = await getSession();
  if (!session) redirect("/signin?callbackUrl=/account");

  const { sub, email, name, role } = session.user;
  return (
    <main>
      <h1>Account</h1>
      <dl>
        <dt>sub</dt><dd>{sub}</dd>
        <dt>email</dt><dd>{email ?? "-"}</dd>
        <dt>name</dt><dd>{name ?? "-"}</dd>
        <dt>role</dt><dd>{role ?? "-"}</dd>
      </dl>
      <p><a href="/">Home</a></p>
    </main>
  );
}

New apps have cacheComponents turned on, which prerenders pages where it can. connection() and instant = false tell Next.js these pages depend on the visitor's cookie and must wait for it. The account page checks the session itself too, so it stays protected if the proxy's matcher is changed.

4. Try it

npm run dev -- -p 3001

Open http://localhost:3001 and choose Sign in. You go to authto.it's sign-in page. Enter your email address (on an invite-only site, one you added to the site), type the code authto.it emails you, and you are back on the home page as Signed in as <your name or email>. /account shows your sub, email, name and role. Sign out passes through authto.it and returns to the home page signed out. Visiting /account now sends you to sign in again.

If authto.it says the return address is not allowed, compare it with the site's return address character by character, including the port.

5. Protect pages and use the role

To protect more pages, add them to the proxy's matcher:

proxy.ts

export const config = { matcher: ["/account/:path*", "/admin/:path*"] };

In a page, route handler or server action, read the person with getSession(). role is set per person on the authto.it dashboard and is null when none is set. It is read at sign-in, so a changed role applies from the person's next sign-in.

app/admin/page.tsx

import { notFound } from "next/navigation";
import { getSession } from "@/lib/auth";

export const instant = false;

export default async function Admin() {
  const session = await getSession();
  if (session?.user.role !== "admin") notFound(); // or redirect("/")

  return <h1>Admin</h1>;
}

Key your own records on session.user.sub. It never changes for a person on a site; their email address can.

Going live

  • Add the production return address (https://example.com/api/auth/callback/authto) and after-sign-out address (https://example.com/) to the site on the dashboard.
  • Set AUTHTO_CLIENT_ID, AUTHTO_CLIENT_SECRET, NEXTAUTH_SECRET and NEXTAUTH_URL=https://example.com in the server's environment. Keep the secrets out of git.
  • Serve the app over HTTPS. With an https:// NEXTAUTH_URL, Auth.js marks its cookies secure.
  • Ask for offline_access (and keep the refresh token) only if the app calls APIs on the person's behalf after sign-in. For sign-in alone it is not needed.
  • Add people, choose invite-only or open, and set roles on the authto.it dashboard.