Files
supabase/examples/realtime/nextjs-auth-presence/pages/index.tsx
Katerina Skroumpelou 41f9ddd70c docs: update setAll callbacks to accept cache headers second argument (#44240)
## What

Updates all `setAll` cookie handler implementations across docs and
examples to accept the new `headers` second argument introduced in
`@supabase/ssr` v0.10.0
([supabase/ssr#176](https://github.com/supabase/ssr/pull/176)).

## Why

`@supabase/ssr` v0.10.0 introduced a breaking change: `setAll` now
receives a required second argument `headers: Record<string, string>`
alongside the cookies array. When a token refresh occurs, the library
passes cache headers (`Cache-Control`, `Expires`, `Pragma`) that must be
applied to the HTTP response to prevent CDN caching of auth responses.

Because TypeScript allows functions with fewer parameters to satisfy a
type expecting more, existing `setAll` implementations do not produce a
type error when the second argument is omitted. Users who copy an
outdated snippet will silently miss the CDN protection.

Root cause and context:
[supabase/supabase-js#1682](https://github.com/supabase/supabase-js/issues/1682)

## Changes

**Proxy/middleware contexts** (where token refreshes happen) now apply
the cache headers to their response:
- Next.js proxy files: `supabaseResponse.headers.set(key, value)`
- SvelteKit hooks: `event.setHeaders(headers)`
- Hono middleware: `c.header(key, value)`
- Pages Router (Express-style): `ctx.res.setHeader(key, value)`
- Remix/React Router loaders and actions: applied to response headers
(outer `headers` variable renamed to `responseHeaders` to avoid naming
conflict with the new param)

**Server Component and API route contexts** (no response object
available) accept `_headers` without applying them.

## Files updated

- `apps/docs/content/guides/auth/server-side/creating-a-client.mdx`
(inline Astro, Remix, React Router, Express snippets)
- `apps/docs/content/_partials/oauth_pkce_flow.mdx`
- `apps/docs/content/guides/auth/oauth-server/getting-started.mdx`
- `apps/docs/content/guides/auth/passwords.mdx`
-
`apps/docs/content/troubleshooting/how-to-migrate-from-supabase-auth-helpers-to-ssr-package-5NRunM.mdx`
- `examples/auth/nextjs/`, `examples/auth/nextjs-full/` (proxy + server)
- `examples/auth/sveltekit/`, `examples/auth/sveltekit-full/`
- `examples/auth/hono/`, `examples/auth/hono-full/`
- `examples/user-management/nextjs-user-management/` (proxy + server)
- `examples/user-management/sveltekit-user-management/`
- `examples/realtime/nextjs-authorization-demo/` (proxy + server)
- `examples/realtime/nextjs-auth-presence/` (pages router)
- `examples/prompts/nextjs-supabase-auth.md`
2026-03-30 16:08:29 +03:00

101 lines
2.7 KiB
TypeScript

import { useSupabaseClient, useUser } from '@/lib/supabase-context'
import { createServerClient } from '@supabase/ssr'
import { serialize } from 'cookie'
import { RealtimePresenceState } from '@supabase/supabase-js'
import type { GetServerSidePropsContext, NextPage } from 'next'
import { useEffect, useState } from 'react'
const HomePage: NextPage = () => {
const supabaseClient = useSupabaseClient()
const this_user = useUser()
const [userState, setUserState] = useState<RealtimePresenceState>({})
useEffect(() => {
console.log('user: ', this_user)
const channel = supabaseClient.channel('online-users', {
config: {
presence: {
key: this_user?.email ? this_user?.email : 'Unknown',
},
},
})
channel.on('presence', { event: 'sync' }, () => {
const presentState = channel.presenceState()
console.log('inside presence: ', presentState)
setUserState({ ...presentState })
})
channel.on('presence', { event: 'join' }, ({ newPresences }) => {
console.log('New users have joined: ', newPresences)
})
channel.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
const status = await channel.track({
user_name: this_user?.email ? this_user?.email : 'Unknown',
})
console.log('status: ', status)
}
})
}, [])
return (
<>
<button onClick={() => supabaseClient.auth.signOut()}>Sign out</button>
<p> List of Currently Logged in Users: </p>
{Object.keys(userState).map((key) => (
<p key={key}>Hi {key}</p>
))}
</>
)
}
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return Object.entries(ctx.req.cookies).map(([name, value]) => ({
name,
value: value ?? '',
}))
},
setAll(cookiesToSet, headers) {
const existing = ctx.res.getHeader('Set-Cookie') ?? []
ctx.res.setHeader('Set-Cookie', [
...(Array.isArray(existing) ? existing : [String(existing)]),
...cookiesToSet.map(({ name, value, options }) => serialize(name, value, options)),
])
Object.entries(headers).forEach(([key, value]) => ctx.res.setHeader(key, value))
},
},
}
)
const {
data: { user },
} = await supabase.auth.getUser()
if (!user)
return {
redirect: {
destination: '/login',
permanent: false,
},
}
return {
props: {
user,
},
}
}
export default HomePage