# Server-side sessions

> Read the signed-in session on your server (server components, route handlers, server actions), in browser-SDK or confidential mode.

Source: https://www.pontive.com/docs/sdk/server-sessions

For an app whose server needs to know who is signed in, or call APIs as them:
server components, route handlers, server actions. Your code asks for the
session and gets one; the SDK decides how it is kept, from one thing — whether
you give it a client secret.

| Your app | Configure | Who signs in and refreshes | What the server reads |
| --- | --- | --- | --- |
| Regular app (embedded widgets), or public oauth app | no client secret | the browser SDK | the access token cookie the auth server keeps current |
| Confidential oauth app | `clientSecret` + `sessionSecret` | the SDK, on your server | an encrypted session cookie it keeps |

Either way `auth()` returns the same session, and either way exactly one thing
spends the refresh token, so refresh-token rotation never signs anyone out.

## Browser-SDK apps [#browser-sdk-apps]

The widgets sign the user in and the browser refreshes, as they always have.
What this adds is the server's view of that session. It needs the auth proxy
(see [auth-proxy.md](/docs/sdk/auth-proxy)): through it the auth server's cookies are
first-party on your origin, including an HttpOnly `__Host-pontive_access`
holding the current access token.

```ts
// lib/pontive.ts
import { pontiveAuth } from "@pontive/pontkit-nextjs/server";

export const pontive = pontiveAuth({
  issuer: process.env.PONTIVE_ISSUER!,       // your auth domain
  clientId: process.env.PONTIVE_CLIENT_ID!,  // the app's id
  // authPath: "/__pontive",                    // where the auth proxy is mounted
});
```

```ts
// proxy.ts (middleware.ts before Next 16)
import type { NextRequest } from "next/server";
import { pontive } from "@/lib/pontive";

export function proxy(req: NextRequest) {
  return pontive.middleware(req);
}
```

`pontive.auth()` then verifies the access token cookie and returns the user and
token. The middleware never refreshes: when a signed-in user loads a page after
the access token has lapsed (they came back to a closed tab, say), it sends the
browser through the auth server's session handshake, which renews the cookies
and returns straight to the page. Fetches and client-side navigations are never
redirected; the browser SDK renews the token for those on its own.

## Confidential oauth apps [#confidential-oauth-apps]

```ts
// lib/pontive.ts
import { pontiveAuth } from "@pontive/pontkit-nextjs/server";

export const pontive = pontiveAuth({
  issuer: process.env.PONTIVE_ISSUER!,          // your auth domain
  clientId: process.env.PONTIVE_CLIENT_ID!,     // the app's id
  clientSecret: process.env.PONTIVE_CLIENT_SECRET!,
  sessionSecret: process.env.PONTIVE_SESSION_SECRET!, // 32+ random characters
  baseUrl: process.env.PUBLIC_URL,              // e.g. https://app.acme.com
});
```

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

export const { GET, POST } = pontive.handlers;
```

```ts
// proxy.ts (middleware.ts before Next 16)
import type { NextRequest } from "next/server";
import { pontive } from "@/lib/pontive";

export function proxy(req: NextRequest) {
  return pontive.middleware(req, (session) => {
    if (!session && !req.nextUrl.pathname.startsWith("/login")) {
      return Response.redirect(new URL(`/api/auth/login?returnTo=${req.nextUrl.pathname}`, req.url));
    }
  });
}
```

```ts
// Anywhere on the server
const session = await pontive.auth();
session?.user.email;
await fetch(api, { headers: { authorization: `Bearer ${session!.accessToken}` } });
```

Register `https://<your origin>/api/auth/callback` as a redirect URI and
`https://<your origin>/login` as a post-logout redirect URI on the app. Sign-in
starts at `/api/auth/login`, sign-out at `/api/auth/logout`.

## What the confidential mode handles for you [#what-the-confidential-mode-handles-for-you]

- **Refresh.** The middleware refreshes the access token shortly before it
  expires, before anything renders, and hands the refreshed session to the page
  rendered for that same request. `auth()` only ever reads, so it works in a
  server component, where cookies cannot be written.
- **Rotation.** Each refresh spends the refresh token it presents. Concurrent
  requests share one refresh, and a request still holding the old cookie a
  moment later gets the same result instead of spending the old token again. A
  refresh token presented twice is otherwise read as stolen, and signs the user
  out.
- **Several replicas.** Refreshes that race across instances are absorbed by
  the auth server's short reuse grace window; no shared lock is needed.
- **Nothing in the page.** Both tokens live only in an HttpOnly cookie,
  encrypted with your session secret. Page JavaScript never sees either.

## Organizations (B2B) [#organizations-b2b]

A session can act in one organization. Its access token then says so (`org_id`)
along with the user's effective `roles` and `permissions` there, which
the auth server re-reads on every refresh, and `session.organization` exposes
them:

```ts
const session = await pontive.auth();
session?.organization; // { id, roles, permissions } | null
```

The user is never asked to pick one. A sign-in starts in the organization the
app names (`/api/auth/login?organization_id=…`, or `organization_id` on
`/authorize`), otherwise in the user's only organization, otherwise in none.
B2C apps never see one: `organization` is `null`.

To move a session, send the browser to the switch route. Both modes support it:
a confidential app refreshes into the organization on its server; a browser-SDK
app goes through the auth server's session handshake, so the browser stays the
only thing that spends its refresh token.

```tsx
import { switchOrganizationPath } from "@pontive/pontkit-nextjs/server";

<a href={switchOrganizationPath("/api/auth", org.id, "/dashboard")}>{org.name}</a>
```

A switch the user cannot make (not a member) returns to `returnTo` with
`?organization_error=not_a_member` and leaves the session exactly as it was.

## Other frameworks [#other-frameworks]

`@pontive/pontkit-server` is the same thing on plain Web `Request`/`Response`:
`createServerAuth(config)` returns `handle(request)` for the sign-in routes,
`getSession(cookieHeader)`, and `refresh(request)` for whatever runs before
your handlers.
