Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

docs: purge safeGetSession + getUser from auth example code (#47042)

Katerina Skroumpelou6eb40f17a7fb
diff --git a/apps/docs/content/guides/auth/oauth-server/getting-started.mdx b/apps/docs/content/guides/auth/oauth-server/getting-started.mdx
index 1d40792deaf..a7f70ebcf6c 100644
--- a/apps/docs/content/guides/auth/oauth-server/getting-started.mdx
+++ b/apps/docs/content/guides/auth/oauth-server/getting-started.mdx
@@ -189,6 +189,8 @@ Here's how to build a minimal authorization page at your configured path (e.g.,
>
<TabPanel id="nextjs" label="Next.js">
+<$Partial path="auth_methods.mdx" />
+
```tsx
// app/oauth/consent/page.tsx
import { createServerClient } from '@supabase/ssr'
@@ -221,11 +223,10 @@ export default async function ConsentPage({
)
// Check if user is authenticated
- const {
- data: { user },
- } = await supabase.auth.getUser()
+ const { data } = await supabase.auth.getClaims()
+ const claims = data?.claims
- if (!user) {
+ if (!claims) {
// Redirect to login, preserving authorization_id
redirect(`/login?redirect=/oauth/consent?authorization_id=${authorizationId}`)
}
diff --git a/apps/docs/content/guides/auth/server-side/creating-a-client.mdx b/apps/docs/content/guides/auth/server-side/creating-a-client.mdx
index 30a6f5d2802..92ce3e4f2d2 100644
--- a/apps/docs/content/guides/auth/server-side/creating-a-client.mdx
+++ b/apps/docs/content/guides/auth/server-side/creating-a-client.mdx
@@ -172,6 +172,8 @@ You need setup code to configure a Supabase client to use cookies. Once you have
Use the browser client in code that runs on the browser, and the server client in code that runs on the server.
+<$Partial path="auth_methods.mdx" />
+
<Tabs
scrollable
size="small"
@@ -196,6 +198,8 @@ The Proxy is responsible for:
2. Passing the refreshed Auth token to Server Components, so they don't attempt to refresh the same token themselves. This is accomplished with `request.cookies.set`.
3. Passing the refreshed Auth token to the browser, so it replaces the old token. This is accomplished with `response.cookies.set`.
+<$Partial path="auth_methods.mdx" />
+
<Accordion>
<AccordionItem
@@ -258,6 +262,8 @@ It's safe to trust `getClaims()` because it validates the JWT signature against
</Admonition>
+<$Partial path="auth_methods.mdx" />
+
<div className="mt-12">
<$CodeTabs>
<$CodeSample path="/auth/nextjs/proxy.ts" meta="name=proxy.ts" language="typescript" />
@@ -291,6 +297,8 @@ Set up server-side hooks in `src/hooks.server.ts`. The hooks:
- Check user authentication.
- Guard protected pages.
+<$Partial path="auth_methods.mdx" />
+
<$CodeSample
path="/auth/sveltekit/src/hooks.server.ts"
meta="name=src/hooks.server.ts"
@@ -843,6 +851,8 @@ language="typescript"
You can now use this middleware in your Hono application to create a server Supabase client that can be used to make authenticated requests.
+<$Partial path="auth_methods.mdx" />
+
<$CodeSample
path="/auth/hono/src/index.tsx"
meta="name=src/index.tsx"
diff --git a/examples/auth/hono-full/src/database.types.ts b/examples/auth/hono-full/src/database.types.ts
new file mode 100644
index 00000000000..06410b30b2d
--- /dev/null
+++ b/examples/auth/hono-full/src/database.types.ts
@@ -0,0 +1,4 @@
+// Replace this file by running:
+// npx supabase gen types typescript --local > src/database.types.ts
+// or pass --project-id <your-project-ref> for a remote project.
+export type Database = Record<string, never>
diff --git a/examples/auth/hono-full/src/index.tsx b/examples/auth/hono-full/src/index.tsx
index 8560a3bcabf..a458903fcb3 100644
--- a/examples/auth/hono-full/src/index.tsx
+++ b/examples/auth/hono-full/src/index.tsx
@@ -6,11 +6,11 @@ app.use('*', supabaseMiddleware())
const routes = app.get('/api/user', async (c) => {
const supabase = getSupabase(c)
- const { data, error } = await supabase.auth.getUser()
+ const { data, error } = await supabase.auth.getClaims()
if (error) console.log('error', error)
- if (!data?.user) {
+ if (!data?.claims) {
return c.json({
message: 'You are not logged in.',
})
@@ -18,7 +18,7 @@ const routes = app.get('/api/user', async (c) => {
return c.json({
message: 'You are logged in!',
- userId: data.user,
+ userId: data.claims.sub,
})
})
diff --git a/examples/auth/hono-full/src/middleware/auth.middleware.ts b/examples/auth/hono-full/src/middleware/auth.middleware.ts
index 89daae8a19f..a9b578e7429 100644
--- a/examples/auth/hono-full/src/middleware/auth.middleware.ts
+++ b/examples/auth/hono-full/src/middleware/auth.middleware.ts
@@ -4,9 +4,11 @@ import type { Context, MiddlewareHandler } from 'hono'
import { env } from 'hono/adapter'
import { setCookie } from 'hono/cookie'
+import type { Database } from '../database.types'
+
declare module 'hono' {
interface ContextVariableMap {
- supabase: SupabaseClient
+ supabase: SupabaseClient<Database>
}
}
diff --git a/examples/auth/hono/src/database.types.ts b/examples/auth/hono/src/database.types.ts
new file mode 100644
index 00000000000..06410b30b2d
--- /dev/null
+++ b/examples/auth/hono/src/database.types.ts
@@ -0,0 +1,4 @@
+// Replace this file by running:
+// npx supabase gen types typescript --local > src/database.types.ts
+// or pass --project-id <your-project-ref> for a remote project.
+export type Database = Record<string, never>
diff --git a/examples/auth/hono/src/middleware/auth.middleware.ts b/examples/auth/hono/src/middleware/auth.middleware.ts
index b8896494b25..f0a01eb0a20 100644
--- a/examples/auth/hono/src/middleware/auth.middleware.ts
+++ b/examples/auth/hono/src/middleware/auth.middleware.ts
@@ -4,9 +4,11 @@ import type { Context, MiddlewareHandler } from 'hono'
import { env } from 'hono/adapter'
import { setCookie } from 'hono/cookie'
+import type { Database } from '../database.types'
+
declare module 'hono' {
interface ContextVariableMap {
- supabase: SupabaseClient
+ supabase: SupabaseClient<Database>
}
}
diff --git a/examples/auth/nextjs-full/app/private/page.tsx b/examples/auth/nextjs-full/app/private/page.tsx
index f025b2dfc6f..b0585f19439 100644
--- a/examples/auth/nextjs-full/app/private/page.tsx
+++ b/examples/auth/nextjs-full/app/private/page.tsx
@@ -8,11 +8,10 @@ import { redirect } from 'next/navigation'
export default async function ProtectedPage() {
const supabase = await createClient()
- const {
- data: { user },
- } = await supabase.auth.getUser()
+ const { data } = await supabase.auth.getClaims()
+ const claims = data?.claims
- if (!user) {
+ if (!claims) {
return redirect('/login')
}
diff --git a/examples/auth/nextjs-full/components/AuthButton.tsx b/examples/auth/nextjs-full/components/AuthButton.tsx
index c07ea4da058..97b296f4b63 100644
--- a/examples/auth/nextjs-full/components/AuthButton.tsx
+++ b/examples/auth/nextjs-full/components/AuthButton.tsx
@@ -5,9 +5,8 @@ import { redirect } from 'next/navigation'
export default async function AuthButton() {
const supabase = await createClient()
- const {
- data: { user },
- } = await supabase.auth.getUser()
+ const { data } = await supabase.auth.getClaims()
+ const claims = data?.claims
const signOut = async () => {
'use server'
@@ -17,9 +16,9 @@ export default async function AuthButton() {
return redirect('/login')
}
- return user ? (
+ return claims ? (
<div className="flex items-center gap-4">
- Hey, {user.email}!
+ Hey, {claims.email}!
<form action={signOut}>
<button className="py-2 px-4 rounded-md no-underline bg-btn-background hover:bg-btn-background-hover">
Logout
diff --git a/examples/auth/sveltekit-full/src/app.d.ts b/examples/auth/sveltekit-full/src/app.d.ts
index 0a7380073be..23d6f558941 100644
--- a/examples/auth/sveltekit-full/src/app.d.ts
+++ b/examples/auth/sveltekit-full/src/app.d.ts
@@ -1,17 +1,15 @@
-import type { Session, SupabaseClient, User } from '@supabase/supabase-js'
-import type { Database } from './database.types.ts' // import generated types
+import type { JwtPayload, SupabaseClient } from '@supabase/supabase-js'
+import type { Database } from './database.types'
declare global {
namespace App {
// interface Error {}
interface Locals {
supabase: SupabaseClient<Database>
- safeGetSession: () => Promise<{ session: Session | null; user: User | null }>
- session: Session | null
- user: User | null
+ claims: JwtPayload | null
}
interface PageData {
- session: Session | null
+ claims: JwtPayload | null
}
// interface PageState {}
// interface Platform {}
diff --git a/examples/auth/sveltekit-full/src/database.types.ts b/examples/auth/sveltekit-full/src/database.types.ts
new file mode 100644
index 00000000000..06410b30b2d
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/database.types.ts
@@ -0,0 +1,4 @@
+// Replace this file by running:
+// npx supabase gen types typescript --local > src/database.types.ts
+// or pass --project-id <your-project-ref> for a remote project.
+export type Database = Record<string, never>
diff --git a/examples/auth/sveltekit-full/src/hooks.server.ts b/examples/auth/sveltekit-full/src/hooks.server.ts
index 153400a63e0..f9ce3ec2d7b 100644
--- a/examples/auth/sveltekit-full/src/hooks.server.ts
+++ b/examples/auth/sveltekit-full/src/hooks.server.ts
@@ -29,31 +29,6 @@ const supabase: Handle = async ({ event, resolve }) => {
},
})
- /**
- * Unlike `supabase.auth.getSession()`, which returns the session _without_
- * validating the JWT, this function also calls `getUser()` to validate the
- * JWT before returning the session.
- */
- event.locals.safeGetSession = async () => {
- const {
- data: { session },
- } = await event.locals.supabase.auth.getSession()
- if (!session) {
- return { session: null, user: null }
- }
-
- const {
- data: { user },
- error,
- } = await event.locals.supabase.auth.getUser()
- if (error) {
- // JWT validation has failed
- return { session: null, user: null }
- }
-
- return { session, user }
- }
-
return resolve(event, {
filterSerializedResponseHeaders(name) {
/**
@@ -66,15 +41,20 @@ const supabase: Handle = async ({ event, resolve }) => {
}
const authGuard: Handle = async ({ event, resolve }) => {
- const { session, user } = await event.locals.safeGetSession()
- event.locals.session = session
- event.locals.user = user
+ /**
+ * `getClaims` validates the JWT signature locally (against the project's
+ * asymmetric signing keys) without an extra round-trip to the Auth server.
+ * Use this for route protection. Use `getUser()` only when you need the
+ * canonical server-validated user record (e.g., after password changes).
+ */
+ const { data: claimsData } = await event.locals.supabase.auth.getClaims()
+ event.locals.claims = claimsData?.claims ?? null
- if (!event.locals.session && event.url.pathname.startsWith('/private')) {
+ if (!event.locals.claims && event.url.pathname.startsWith('/private')) {
redirect(303, '/auth')
}
- if (event.locals.session && event.url.pathname === '/auth') {
+ if (event.locals.claims && event.url.pathname === '/auth') {
redirect(303, '/private')
}
diff --git a/examples/auth/sveltekit-full/src/routes/+layout.server.ts b/examples/auth/sveltekit-full/src/routes/+layout.server.ts
index d30c583e958..766576e7dd5 100644
--- a/examples/auth/sveltekit-full/src/routes/+layout.server.ts
+++ b/examples/auth/sveltekit-full/src/routes/+layout.server.ts
@@ -1,10 +1,8 @@
import type { LayoutServerLoad } from './$types'
-export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
- const { session, user } = await safeGetSession()
+export const load: LayoutServerLoad = async ({ locals: { claims }, cookies }) => {
return {
- session,
- user,
+ claims,
cookies: cookies.getAll(),
}
}
diff --git a/examples/auth/sveltekit-full/src/routes/+layout.svelte b/examples/auth/sveltekit-full/src/routes/+layout.svelte
index f2ee8acd1f6..48547895610 100644
--- a/examples/auth/sveltekit-full/src/routes/+layout.svelte
+++ b/examples/auth/sveltekit-full/src/routes/+layout.svelte
@@ -3,11 +3,11 @@
import { onMount } from 'svelte'
let { data, children } = $props()
- let { session, supabase } = $derived(data)
+ let { claims, supabase } = $derived(data)
onMount(() => {
const { data } = supabase.auth.onAuthStateChange((_, newSession) => {
- if (newSession?.expires_at !== session?.expires_at) {
+ if (newSession?.expires_at !== claims?.exp) {
invalidate('supabase:auth')
}
})
@@ -16,4 +16,4 @@
})
</script>
-{@render children()}
\ No newline at end of file
+{@render children()}
diff --git a/examples/auth/sveltekit-full/src/routes/+layout.ts b/examples/auth/sveltekit-full/src/routes/+layout.ts
index d1a6c76ae7a..e5262dc0eb9 100644
--- a/examples/auth/sveltekit-full/src/routes/+layout.ts
+++ b/examples/auth/sveltekit-full/src/routes/+layout.ts
@@ -27,17 +27,14 @@ export const load: LayoutLoad = async ({ data, depends, fetch }) => {
})
/**
- * It's fine to use `getSession` here, because on the client, `getSession` is
- * safe, and on the server, it reads `session` from the `LayoutData`, which
- * safely checked the session using `safeGetSession`.
+ * `getClaims` validates the JWT signature locally (for asymmetric keys) once
+ * the relevant signing keys are available or cached, and returns the decoded
+ * claims. While an initial or periodic network request may be required to
+ * fetch or refresh keys, this is both faster and safer than `getSession`,
+ * which does not validate the JWT.
*/
- const {
- data: { session },
- } = await supabase.auth.getSession()
+ const { data: claimsData, error } = await supabase.auth.getClaims()
+ const claims = error ? null : claimsData?.claims
- const {
- data: { user },
- } = await supabase.auth.getUser()
-
- return { session, supabase, user }
+ return { supabase, claims }
}
diff --git a/examples/auth/sveltekit-full/src/routes/private/+page.svelte b/examples/auth/sveltekit-full/src/routes/private/+page.svelte
index e924b9e8285..0fdecafd3e0 100644
--- a/examples/auth/sveltekit-full/src/routes/private/+page.svelte
+++ b/examples/auth/sveltekit-full/src/routes/private/+page.svelte
@@ -5,7 +5,7 @@
import type { PageData } from './$types'
let { data } = $props()
- let { notes, supabase, user } = $derived(data)
+ let { notes, supabase, claims } = $derived(data)
const handleSubmit: EventHandler<SubmitEvent, HTMLFormElement> = async (evt) => {
evt.preventDefault()
@@ -24,7 +24,7 @@
}
</script>
-<h1>Private page for user: {user?.email}</h1>
+<h1>Private page for user: {claims?.email}</h1>
<h2>Notes</h2>
<ul>
{#each notes as note}
@@ -36,4 +36,4 @@
Add a note
<input name="note" type="text" />
</label>
-</form>
\ No newline at end of file
+</form>
diff --git a/examples/auth/sveltekit/src/app.d.ts b/examples/auth/sveltekit/src/app.d.ts
index 0a7380073be..226213b66e3 100644
--- a/examples/auth/sveltekit/src/app.d.ts
+++ b/examples/auth/sveltekit/src/app.d.ts
@@ -1,17 +1,11 @@
-import type { Session, SupabaseClient, User } from '@supabase/supabase-js'
-import type { Database } from './database.types.ts' // import generated types
+import type { SupabaseClient } from '@supabase/supabase-js'
+import type { Database } from './database.types'
declare global {
namespace App {
// interface Error {}
interface Locals {
supabase: SupabaseClient<Database>
- safeGetSession: () => Promise<{ session: Session | null; user: User | null }>
- session: Session | null
- user: User | null
- }
- interface PageData {
- session: Session | null
}
// interface PageState {}
// interface Platform {}
diff --git a/examples/auth/sveltekit/src/database.types.ts b/examples/auth/sveltekit/src/database.types.ts
new file mode 100644
index 00000000000..06410b30b2d
--- /dev/null
+++ b/examples/auth/sveltekit/src/database.types.ts
@@ -0,0 +1,4 @@
+// Replace this file by running:
+// npx supabase gen types typescript --local > src/database.types.ts
+// or pass --project-id <your-project-ref> for a remote project.
+export type Database = Record<string, never>
diff --git a/examples/auth/sveltekit/src/hooks.server.ts b/examples/auth/sveltekit/src/hooks.server.ts
index 3cf3c045bf3..e733aedd5fd 100644
--- a/examples/auth/sveltekit/src/hooks.server.ts
+++ b/examples/auth/sveltekit/src/hooks.server.ts
@@ -12,7 +12,7 @@ export const handle: Handle = async ({ event, resolve }) => {
/**
* Note: You have to add the `path` variable to the
* set and remove method due to sveltekit's cookie API
- * requiring this to be set, setting the path to an empty string
+ * requiring this to be set, setting the path to `/`
* will replicate previous/standard behavior (https://kit.svelte.dev/docs/types#public-types-cookies)
*/
cookiesToSet.forEach(({ name, value, options }) =>
@@ -25,31 +25,6 @@ export const handle: Handle = async ({ event, resolve }) => {
},
})
- /**
- * Unlike `supabase.auth.getSession()`, which returns the session _without_
- * validating the JWT, this function also calls `getUser()` to validate the
- * JWT before returning the session.
- */
- event.locals.safeGetSession = async () => {
- const {
- data: { session },
- } = await event.locals.supabase.auth.getSession()
- if (!session) {
- return { session: null, user: null }
- }
-
- const {
- data: { user },
- error,
- } = await event.locals.supabase.auth.getUser()
- if (error) {
- // JWT validation has failed
- return { session: null, user: null }
- }
-
- return { session, user }
- }
-
return resolve(event, {
filterSerializedResponseHeaders(name) {
return name === 'content-range' || name === 'x-supabase-api-version'
diff --git a/examples/auth/sveltekit/src/routes/+layout.server.ts b/examples/auth/sveltekit/src/routes/+layout.server.ts
index 9fe704d8d6c..1472797aaf3 100644
--- a/examples/auth/sveltekit/src/routes/+layout.server.ts
+++ b/examples/auth/sveltekit/src/routes/+layout.server.ts
@@ -1,11 +1,7 @@
import type { LayoutServerLoad } from './$types'
-export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
- const { session, user } = await safeGetSession()
-
+export const load: LayoutServerLoad = async ({ cookies }) => {
return {
- session,
- user,
cookies: cookies.getAll(),
}
}
diff --git a/examples/auth/sveltekit/src/routes/+layout.ts b/examples/auth/sveltekit/src/routes/+layout.ts
index 2873bba98f1..b8a74cfb892 100644
--- a/examples/auth/sveltekit/src/routes/+layout.ts
+++ b/examples/auth/sveltekit/src/routes/+layout.ts
@@ -23,13 +23,14 @@ export const load: LayoutLoad = async ({ fetch, data, depends }) => {
})
/**
- * It's fine to use `getSession` here, because on the client, `getSession` is
- * safe, and on the server, it reads `session` from the `LayoutData`, which
- * safely checked the session using `safeGetSession`.
+ * `getClaims` validates the JWT signature locally (for asymmetric keys) once
+ * the relevant signing keys are available or cached, and returns the decoded
+ * claims. While an initial or periodic network request may be required to
+ * fetch or refresh keys, this is both faster and safer than `getSession`,
+ * which does not validate the JWT.
*/
- const {
- data: { session },
- } = await supabase.auth.getSession()
+ const { data: claimsData, error } = await supabase.auth.getClaims()
+ const claims = error ? null : claimsData?.claims
- return { supabase, session }
+ return { supabase, claims }
}
diff --git a/examples/user-management/sveltekit-user-management/src/app.d.ts b/examples/user-management/sveltekit-user-management/src/app.d.ts
index 617d908c9d6..fdece1f785f 100644
--- a/examples/user-management/sveltekit-user-management/src/app.d.ts
+++ b/examples/user-management/sveltekit-user-management/src/app.d.ts
@@ -1,11 +1,14 @@
import type { SupabaseClient } from '@supabase/supabase-js'
+
+import type { Database } from './database.types'
+
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
interface Locals {
- supabase: SupabaseClient
+ supabase: SupabaseClient<Database>
}
// interface PageState {}
// interface Platform {}
diff --git a/examples/user-management/sveltekit-user-management/src/database.types.ts b/examples/user-management/sveltekit-user-management/src/database.types.ts
new file mode 100644
index 00000000000..06410b30b2d
--- /dev/null
+++ b/examples/user-management/sveltekit-user-management/src/database.types.ts
@@ -0,0 +1,4 @@
+// Replace this file by running:
+// npx supabase gen types typescript --local > src/database.types.ts
+// or pass --project-id <your-project-ref> for a remote project.
+export type Database = Record<string, never>