Alle Artikel
19. November 2026

Supabase auth in Next.js: safe server-side sessions, 2026

Verify Supabase sessions on the server with getClaims(), refresh them in the proxy, and authorize next to your data.

Row of outlined and filled vertical bars with one acid bar on a dotted canvas
Illustration: Kallos Labs.

Introduction

To run Supabase auth in Next.js safely, refresh the session in the proxy, verify it on the server with getClaims(), and make the real authorization decision next to your data. Treat the session cookie as user input, because anyone can forge it.

This guide is for teams shipping a Next.js App Router product on Supabase. It covers the two clients, the proxy, the three ways to read a session, where authorization belongs, and one caching mistake that can sign a visitor in as someone else. Details reflect the Supabase and Next.js docs as of November 2026.

Set up the two clients

Packages and environment variables

Node map diagram with three parts: Server Components, Server Actions and Route Handlers
Node map: Set up the two clients.

Install @supabase/supabase-js and @supabase/ssr. In Next.js the Supabase server-side auth guide names two public variables: NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY. The publishable key is meant to ship to the browser. Authorization comes from the user's session and your database policies, not from hiding that key.

Browser client and per-request server client

Use createBrowserClient in code that runs in the browser. It is a singleton, so repeated calls return one instance.

Use createServerClient everywhere on the server: Server Components, Server Actions and Route Handlers. It takes a cookies object with getAll and setAll, which lets @supabase/ssr read and write the session cookie. By default that cookie is named sb-<project_ref>-auth-token.

Create a new server client for every request. It has to use that request's cookies, and the client creation guide says creating one is lightweight. A module-level server client is how one user's session ends up in another user's request.

import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'

export async function createClient() {
  const cookieStore = await cookies()

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll: () => cookieStore.getAll(),
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            )
          } catch {
            // Server Components cannot set cookies. The proxy does it.
          }
        },
      },
    }
  )
}

The try/catch is deliberate. Server Components can't write cookies or headers, so the guide ignores that error and leaves the writing to the proxy.

Refresh the session in the proxy

Why a proxy is required

Access tokens expire. Something has to refresh them and hand the new cookies to both the rest of the request and the browser. Server Components can't write cookies, so a proxy does it. It calls supabase.auth.getClaims(), which refreshes the token when needed, then writes the refreshed cookies to the request and the response.

Next.js 15 and Next.js 16 name the file differently

On Next.js 16 the file is proxy.ts. On Next.js 15 and earlier it is middleware.ts, with a function named middleware. Get this wrong and the file is never called. The Supabase guide says sessions then don't refresh and users get signed out,.

Add a matcher so the proxy skips routes that don't use Supabase, such as static assets.

Return the response that setAll built

The proxy builds a supabaseResponse inside setAll. Return that object. If you return a different response, copy its cookies and cache headers onto it first, or the refreshed session never reaches the browser.

Refresh in one place only. Refresh tokens are generally single-use, and reusing one outside Supabase's allowed windows revokes the session. A proxy that refreshes and a client component that also refreshes on its own is a common way to log users out at random.

Pick the right check: getClaims, getUser or getSession

Supabase gives you three ways to read a session on the server. They are not interchangeable.

MethodWhat it doesUse it for
getClaims()Verifies the access token's signature and expiry, and refreshes the session near expiryProtecting pages and data
getUser()Calls the Auth server and returns the current user recordSensitive actions, detecting a revoked session
getSession()Returns the raw session from the cookie without revalidating itReading tokens to forward, never deciding identity

The getClaims reference explains where the verification happens. If your project uses asymmetric signing keys, the default for new projects, getClaims() verifies the token locally against a cached copy of the project's public keys. If the project signs with a symmetric secret, it sends a request to the Auth server, much like getUser().

The revoked session gap

getClaims() checks the signature and the expiry. An unexpired token therefore stays valid even after the session behind it was revoked. The only way to notice a sign-out on another device is to ask the Auth server with getUser(). For routine page protection, getClaims() is the right default. For actions where a stale session matters, such as changing an email address or confirming a payout, call getUser().

Why getSession is wrong on the server

getSession() reads the session out of the cookie. The guide is blunt that the cookie can be forged, so the data inside can't be trusted without verification. Never rely on it for authorization in server code such as the proxy. Reach for it only when you need the tokens themselves, for example to pass an access token to another service.

const supabase = await createClient()
const { data } = await supabase.auth.getClaims()

if (!data?.claims) {
  redirect('/login')
}

Authorize next to the data

The proxy is a fine place to redirect people early. It shouldn't be your only check. The Next.js authentication guide calls proxy checks optimistic: read the session, avoid database lookups, and do the majority of security checks as close as possible to the data source.

In practice that means a few habits:

  • Keep a small data access layer. One server-only function verifies the session and returns the user ID, and every data function calls it. React's cache dedupes the call within a single render pass. It does nothing in Server Actions and Route Handlers, which are not part of a render pass, so they run it every time.
  • Don't rely on layouts. Layouts don't re-render on navigation, so a check that lives only there is skipped on the next route change. Returning null from a layout also doesn't stop nested route segments or Server Actions from being reached.
  • Treat Server Actions and Route Handlers like public endpoints. Each one verifies the session and the permission itself. Hiding a button in the UI isn't authorization.
  • Return only what the caller needs. Select explicit columns instead of whole user rows.

Row Level Security in Postgres is the other half of this. Your server code asks "is this person signed in", and the database policy answers "may this person read this row". If you also build a native client against the same backend, the same split applies, as covered in sharing auth and data contracts between a Next.js backend and a SwiftUI app.

A refresh can put a Set-Cookie header on a response. If that response lands in a shared cache, the next visitor can receive the first visitor's session. The Supabase guide warns that on ISR or behind a CDN, a cached response carrying a refreshed cookie can sign one user in as another.

The fix is built into the client. setAll receives Cache-Control, Expires and Pragma headers along with the cookies. Apply them to every response you return, including any custom response you build in the proxy. Keep pages that read the session out of static and ISR caching, and see what each layer stores in this overview of Next.js caching layers.

Conclusion

Four rules cover most of it. Refresh the session in one place, the proxy. Verify with getClaims(), and step up to getUser() when a revoked session would hurt. Authorize at the data, in every action and handler. Never let a response with a session cookie sit in a shared cache.

If you are weighing an auth build for a product, Kallos Labs does this kind of work under web development, and you can reach the team through the contact page.

Frequently asked questions

Is getSession() safe to use on the server in Next.js?

No, not for deciding who the user is. It reads the session from the cookie without revalidating it, and the cookie can be forged. Use getClaims() to protect pages and data, or getUser() when you need the current user record.

What is the difference between getClaims() and getUser()?

getClaims() verifies the access token's signature and expiry, locally when the project uses asymmetric signing keys. getUser() asks the Auth server, so it also notices a session that was revoked. Pick getUser() for sensitive actions.

Do I need proxy.ts or middleware.ts for Supabase auth?

Yes. Server Components can't write cookies, so a proxy refreshes the token and passes the new cookies on. The file is proxy.ts on Next.js 16 and middleware.ts on Next.js 15 and earlier.

Can a CDN or cache break Supabase sessions?

It can. A cached response that carries a Set-Cookie header can sign one visitor in as another. Apply the Cache-Control, Expires and Pragma headers that setAll provides to every response.