# Quickstart: Next.js

> Add Pontive sign-in to a Next.js App Router app, with the auth endpoints on your own origin, the session readable on the server and the account menu in the header.

Source: https://www.pontive.com/docs/quickstart/nextjs

By the end of this page your Next.js app has sign-in and sign-up pages, a header that knows who is
signed in, and server components that read the session. It follows the working
[Pontive Next.js demo](https://github.com/revotech-group/pontive-next-demo): `@pontive/pontkit-nextjs`
for the components and the server, and a rewrite that serves Pontive's auth endpoints from your app's
own origin so every auth cookie is first-party.

The code is for the App Router.

## 1. Set up the app in Pontive [#1-set-up-the-app-in-pontive]

In the Pontive dashboard, on a **non-production instance** of your project (see
[development and production](/docs#development-and-production-instances)):

1. Create an app for this site and copy its **app id** (`app_…`).
2. Copy the instance's **auth domain**, e.g. `acme-x7k2p9qa-dev.auth.us.pontive.dev`.
3. Add your origins to the app's **allowed origins**: `https://localhost:3000` for local development
   (the dev server below serves HTTPS, and `http://` would be a different origin) and each deployed URL.
   An origin that is not registered is refused with `403 permission_denied`.
4. If you use the account menu (step 5), add `offline_access`, `pontive:me:read` and
   `pontive:me:manage` to the app's **allowed scopes** and turn **refresh tokens** on. A sign-in that
   asks for a scope the app does not allow is refused.

<Callout type="warn" title="Draft">
The dashboard labels in this step are written from the API's field names (allowed origins, allowed
scopes, refresh tokens) and have not been checked against the current dashboard.
</Callout>

## 2. Install the SDK [#2-install-the-sdk]

```sh
npm install @pontive/pontkit-nextjs
```

`@pontive/pontkit-nextjs` brings `@pontive/pontkit-react` (the components) and
`@pontive/pontkit-server` (sessions). The components themselves are web components that the SDK loads
from Pontive's CDN at the release the platform names; there is nothing else to install.

## 3. Environment variables [#3-environment-variables]

```sh title=".env.local"
# The instance's auth domain. Read by next.config.mjs and the server; never sent to the browser.
PONTIVE_AUTH_HOST=acme-x7k2p9qa-dev.auth.us.pontive.dev

# What the browser SDK calls: a path on this app's own origin, rewritten onto PONTIVE_AUTH_HOST.
NEXT_PUBLIC_PONTIVE_AUTH_DOMAIN=/__pontive
NEXT_PUBLIC_PONTIVE_APP_ID=app_...

# The management API host the account widgets call with the user's token.
NEXT_PUBLIC_PONTIVE_API_BASE_URL=https://api.us.pontive.com
```

None of these is a secret: the app id and the auth domain are public. Keep `PONTIVE_AUTH_HOST` without
the `NEXT_PUBLIC_` prefix so the browser only ever knows the `/__pontive` path.

## 4. Serve the auth endpoints from your origin [#4-serve-the-auth-endpoints-from-your-origin]

```js title="next.config.mjs"
import { authProxyRewrites } from "@pontive/pontkit-nextjs/server";

const nextConfig = {
  async rewrites() {
    return authProxyRewrites({ authHost: process.env.PONTIVE_AUTH_HOST });
  },
};

export default nextConfig;
```

This forwards `/__pontive/v1/frontend/*`, `/__pontive/v1/me/*` and `/__pontive/oauth2/*` to the auth
domain. A rewrite to an external destination sends the destination's `Host`, which is what the auth
server needs to know which instance it is answering for. If `next.config` already has `rewrites`,
spread `authProxyRewrites(...)` into the array it returns. Why this matters, and recipes for other
hosts: [the auth proxy](/docs/sdk/auth-proxy).

## 5. The provider, sign-in and sign-up [#5-the-provider-sign-in-and-sign-up]

The components use hooks, so they are mounted from a client component.

```tsx title="components/providers.tsx"
"use client";

import { Provider } from "@pontive/pontkit-nextjs";

/**
 * `scope` replaces the default `openid email profile`, so those stay listed.
 * `offline_access pontive:me:read pontive:me:manage` let the account menu read
 * and change the signed-in user; the app must allow all three (step 1).
 */
const SCOPE = "openid email profile offline_access pontive:me:read pontive:me:manage";

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <Provider
      domain={process.env.NEXT_PUBLIC_PONTIVE_AUTH_DOMAIN!}
      appId={process.env.NEXT_PUBLIC_PONTIVE_APP_ID!}
      apiBaseUrl={process.env.NEXT_PUBLIC_PONTIVE_API_BASE_URL!}
      signinUrl="/signin"
      signupUrl="/signup"
      signinRedirectUrl="/"
      scope={SCOPE}
    >
      {children}
    </Provider>
  );
}
```

```tsx title="components/site-header.tsx"
"use client";

import Link from "next/link";
import { AccountMenu, SignedIn, SignedOut } from "@pontive/pontkit-nextjs";

export function SiteHeader() {
  return (
    <header>
      <Link href="/">Home</Link>
      <SignedOut>
        <Link href="/signin">Sign in</Link>
        <Link href="/signup">Sign up</Link>
      </SignedOut>
      <SignedIn>
        <AccountMenu />
      </SignedIn>
    </header>
  );
}
```

```tsx title="app/layout.tsx"
import { Providers } from "@/components/providers";
import { SiteHeader } from "@/components/site-header";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>
          <SiteHeader />
          {children}
        </Providers>
      </body>
    </html>
  );
}
```

```tsx title="app/signin/page.tsx"
"use client";

import { Signin } from "@pontive/pontkit-nextjs";

export default function SignInPage() {
  return <Signin />;
}
```

```tsx title="app/signup/page.tsx"
"use client";

import { Signup } from "@pontive/pontkit-nextjs";

export default function SignUpPage() {
  return <Signup />;
}
```

`<Signin>` and `<Signup>` render the sign-in and sign-up flows configured on the instance, with its
branding. After sign-in the user is sent to `signinRedirectUrl`. `SignedIn` and `SignedOut` render
nothing until the session has been restored, so there is no flash of the wrong state.

## 6. Read the session on the server [#6-read-the-session-on-the-server]

```ts title="lib/pontive.ts"
import { pontiveAuth, type PontiveAuth } from "@pontive/pontkit-nextjs/server";

// Built on first use, so PONTIVE_AUTH_HOST is read at request time rather than at build.
let instance: PontiveAuth | null = null;

export function pontive(): PontiveAuth {
  instance ??= pontiveAuth({
    issuer: `https://${process.env.PONTIVE_AUTH_HOST}`, // the instance's issuer is its auth domain
    clientId: process.env.NEXT_PUBLIC_PONTIVE_APP_ID!,
    authPath: process.env.NEXT_PUBLIC_PONTIVE_AUTH_DOMAIN || "/__pontive",
  });
  return instance;
}
```

```ts title="proxy.ts"
import type { NextRequest } from "next/server";

import { pontive } from "@/lib/pontive";

// Next 16 calls this file proxy.ts; on Next 15 it is middleware.ts, exporting `middleware`.
export function proxy(req: NextRequest) {
  return pontive().middleware(req);
}

export const config = {
  // Not the auth endpoints themselves, Next's internals or static files.
  matcher: ["/((?!__pontive|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|css|js|map|txt)$).*)"],
};
```

```ts title="app/api/auth/[...pontive]/route.ts"
import { pontive } from "@/lib/pontive";

// The SDK's server routes, such as /api/auth/switch-organization.
export function GET(request: Request) {
  return pontive().handlers.GET(request);
}

export function POST(request: Request) {
  return pontive().handlers.POST(request);
}
```

```tsx title="app/account/page.tsx"
import { pontive } from "@/lib/pontive";

export const dynamic = "force-dynamic";

export default async function AccountPage() {
  const session = await pontive().auth();
  if (!session) return <p>Not signed in.</p>;

  return (
    <div>
      <p>Signed in as {session.user.email ?? session.user.id}</p>
      {session.organization ? (
        <p>
          Organization {session.organization.id}, roles {session.organization.roles.join(", ") || "none"}
        </p>
      ) : null}
    </div>
  );
}
```

There is no client secret here, so the SDK runs in **browser mode**: the components sign the user in
and are the only thing that refreshes tokens. Through the `/__pontive` rewrite the auth server keeps an
HttpOnly access-token cookie on your origin; `auth()` verifies it against the instance's keys, and the
proxy sends a signed-in page load whose token has lapsed through the auth server's session handshake
and straight back. For a confidential app whose server signs in and refreshes itself, see
[server sessions](/docs/sdk/server-sessions).

## 7. Run it [#7-run-it]

```sh
npx next dev --experimental-https
```

Open `https://localhost:3000/signup`, create an account, and you land back on `/` signed in, with the
account menu in the header.

To check the rewrite and the `Host` it sends, against your running app:

```sh
curl -ik -X POST https://localhost:3000/__pontive/oauth2/token
# 400 with "grant_type is required" means the request reached your instance's auth server
```

HTML back instead means the rewrite did not match and Next served the app itself.

## Deploying [#deploying]

Set the same four variables in your host's environment, and register the deployed URL as an allowed
origin on the app. That one registration covers both the auth server and the management API's origin
check on the account widgets' calls. Use a production instance's app and auth domain only for the
production deployment.

## Next steps [#next-steps]

- [Organizations and roles](/docs/guides/organizations-and-roles): `session.organization`, the
  organization switcher and member management.
- [Protect an API](/docs/guides/protect-an-api): verify the user's token in your own API.
- [The framework bindings](/docs/sdk/bindings): every component, prop and event.
