The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix: better handling of getSession for sveltekit (#22381)
Charisa1060c86de14
diff --git a/apps/docs/content/guides/auth/auth-helpers/sveltekit.mdx b/apps/docs/content/guides/auth/auth-helpers/sveltekit.mdxindex 99d5fcc0583..d3b5bb74edb 100644--- a/apps/docs/content/guides/auth/auth-helpers/sveltekit.mdx+++ b/apps/docs/content/guides/auth/auth-helpers/sveltekit.mdx@@ -60,8 +60,6 @@ PUBLIC_SUPABASE_ANON_KEY=your-anon-keyCreate a new `hooks.server.js` file in the root of your project and populate with the following to retrieve the user session.-The session information from `getSession` is supplied to the Supabase client so it can retrieve the auth token. This is safe, since the auth token signature will be revalidated on the Auth server. But you shouldn't trust the unsigned data that is stored alongside the auth token:-<GetSessionWarning />```js src/hooks.server.js@@ -77,15 +75,23 @@ export const handle = async ({ event, resolve }) => {})/**- * a little helper that is written for convenience so that instead- * of calling `const { data: { session } } = await supabase.auth.getSession()`- * you just call this `await getSession()`+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await supabase.auth.getUser()+ if (error) {+ return { session: null, user: null }+ }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -116,15 +122,23 @@ export const handle: Handle = async ({ event, resolve }) => {})/**- * a little helper that is written for convenience so that instead- * of calling `const { data: { session } } = await supabase.auth.getSession()`- * you just call this `await getSession()`+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await supabase.auth.getUser()+ if (error) {+ return { session: null, user: null }+ }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -203,17 +217,18 @@ In order to get the most out of TypeScript and it's intellisense, you should imp```ts src/app.d.ts// src/app.d.ts-import { SupabaseClient, Session } from '@supabase/supabase-js'+import { SupabaseClient, Session, User } from '@supabase/supabase-js'import { Database } from './DatabaseDefinitions'declare global {namespace App {interface Locals {supabase: SupabaseClient<Database>- getSession(): Promise<Session | null>+ safeGetSession(): Promise<{ session: Session | null; user: User | null }>}interface PageData {session: Session | null+ user: User | null}// interface Error {}// interface Platform {}@@ -248,9 +263,12 @@ To make the session available across the UI, including pages and layouts, it is```js src/routes/+layout.server.js// src/routes/+layout.server.js-export const load = async ({ locals: { getSession } }) => {+export const load = async ({ locals: { safeGetSession } }) => {+ const { session, user } = await safeGetSession()+return {- session: await getSession(),+ session,+ user,}}```@@ -260,9 +278,12 @@ export const load = async ({ locals: { getSession } }) => {```ts src/routes/+layout.server.ts// src/routes/+layout.server.ts-export const load = async ({ locals: { getSession } }) => {+export const load = async ({ locals: { safeGetSession } }) => {+ const { session, user } = await safeGetSession()+return {- session: await getSession(),+ session,+ user,}}```@@ -298,6 +319,11 @@ export const load = async ({ fetch, data, depends }) => {serverSession: data.session,})+ /**+ * 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`.+ */const {data: { session },} = await supabase.auth.getSession()@@ -326,6 +352,11 @@ export const load = async ({ fetch, data, depends }) => {serverSession: data.session,})+ /**+ * 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`.+ */const {data: { session },} = await supabase.auth.getSession()@@ -546,8 +577,8 @@ Wrap an API Route to check that the user has a valid session. If they're not log// src/routes/api/protected-route/+server.tsimport { json, error } from '@sveltejs/kit'-export const GET = async ({ locals: { supabase, getSession } }) => {- const session = await getSession()+export const GET = async ({ locals: { supabase, safeGetSession } }) => {+ const { session } = await safeGetSession()if (!session) {// the user is not signed inthrow error(401, { message: 'Unauthorized' })@@ -569,8 +600,8 @@ Wrap an Action to check that the user has a valid session. If they're not loggedimport { error, fail } from '@sveltejs/kit'export const actions = {- createPost: async ({ request, locals: { supabase, getSession } }) => {- const session = await getSession()+ createPost: async ({ request, locals: { supabase, safeGetSession } }) => {+ const { session } = await safeGetSession()if (!session) {// the user is not signed in@@ -629,15 +660,21 @@ async function supabase({ event, resolve }) {})/**- * a little helper that is written for convenience so that instead- * of calling `const { data: { session } } = await supabase.auth.getSession()`- * you just call this `await getSession()`+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await event.locals.supabase.auth.getUser()+ if (error) return { session: null, user: null }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -650,7 +687,7 @@ async function supabase({ event, resolve }) {async function authorization({ event, resolve }) {// protect requests to all routes that start with /protected-routesif (event.url.pathname.startsWith('/protected-routes') && event.request.method === 'GET') {- const session = await event.locals.getSession()+ const { session } = await event.locals.safeGetSession()if (!session) {// the user is not signed inredirect(303, '/')@@ -659,7 +696,7 @@ async function authorization({ event, resolve }) {// protect POST requests to all routes that start with /protected-postsif (event.url.pathname.startsWith('/protected-posts') && event.request.method === 'POST') {- const session = await event.locals.getSession()+ const { session } = await event.locals.safeGetSession()if (!session) {// the user is not signed inthrow error(303, '/')@@ -691,15 +728,21 @@ async function supabase({ event, resolve }) {})/**- * a little helper that is written for convenience so that instead- * of calling `const { data: { session } } = await supabase.auth.getSession()`- * you just call this `await getSession()`+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await event.locals.supabase.auth.getUser()+ if (error) return { session: null, user: null }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -712,7 +755,7 @@ async function supabase({ event, resolve }) {async function authorization({ event, resolve }) {// protect requests to all routes that start with /protected-routesif (event.url.pathname.startsWith('/protected-routes') && event.request.method === 'GET') {- const session = await event.locals.getSession()+ const { session } = await event.locals.safeGetSession()if (!session) {// the user is not signed inredirect(303, '/')@@ -721,7 +764,7 @@ async function authorization({ event, resolve }) {// protect POST requests to all routes that start with /protected-postsif (event.url.pathname.startsWith('/protected-posts') && event.request.method === 'POST') {- const session = await event.locals.getSession()+ const { session } = await event.locals.safeGetSession()if (!session) {// the user is not signed inthrow error(303, '/')@@ -910,15 +953,21 @@ export const handle: Handle = async ({ event, resolve }) => {})/**- * a little helper that is written for convenience so that instead- * of calling `const { data: { session } } = await supabase.auth.getSession()`- * you just call this `await getSession()`+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await event.locals.supabase.auth.getUser()+ if (error) return { session: null, user: null }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -1069,17 +1118,18 @@ declare namespace App {```ts src/app.d.ts// src/app.d.ts-import { SupabaseClient, Session } from '@supabase/supabase-js'+import { SupabaseClient, Session, User } from '@supabase/supabase-js'import { Database } from './DatabaseDefinitions'declare global {namespace App {interface Locals {supabase: SupabaseClient<Database>- getSession(): Promise<Session | null>+ safeGetSession(): Promise<{ session: Session | null; user: User | null }>}interface PageData {session: Session | null+ user: User | null}// interface Error {}// interface Platform {}@@ -1210,7 +1260,7 @@ import type { RequestHandler } from './$types'import { json, error } from '@sveltejs/kit'export const GET: RequestHandler = async ({ locals: { supabase, getSession } }) => {- const session = await getSession()+ const { session } = await getSession()if (!session) {// the user is not signed inthrow error(401, { message: 'Unauthorized' })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.mdxindex b8917844105..09e0775b398 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@@ -429,12 +429,6 @@ export default function Index () {Creating a Supabase client with the `ssr` package automatically configures it to use Cookies. This means your user's session is available throughout the entire SvelteKit stack - page, layout, server, hooks.-<Admonition type="danger">--Beware when accessing the session object on the server, because it is not revalidated on every request from the client. That means the sender can tamper with unencoded data in the session object. If you need to verify the integrity of user data for server logic, call `auth.getUser` instead, which will query the Supabase Auth server for trusted user data.--</Admonition>-<Tabsscrollablesize="small"@@ -475,15 +469,23 @@ export const handle: Handle = async ({ event, resolve }) => {})/**- * a little helper that is written for convenience so that instead- * of calling `const { data: { session } } = await supabase.auth.getSession()`- * you just call this `await getSession()`+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await supabase.auth.getUser()+ if (error) {+ return { session: null, user: null }+ }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -528,6 +530,11 @@ 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`.+ */const {data: { session },} = await supabase.auth.getSession()@@ -543,9 +550,12 @@ export const load: LayoutLoad = async ({ fetch, data, depends }) => {```ts +layout.server.tsimport type { LayoutServerLoad } from './$types'-export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {+export const load: LayoutServerLoad = async ({ locals: { safeGetSession } }) => {+ const { session, user } = await safeGetSession()+return {- session: await getSession(),+ session,+ user,}}```diff --git a/apps/docs/content/guides/getting-started/tutorials/with-sveltekit.mdx b/apps/docs/content/guides/getting-started/tutorials/with-sveltekit.mdxindex b6e24481a01..21b134ede11 100644--- a/apps/docs/content/guides/getting-started/tutorials/with-sveltekit.mdx+++ b/apps/docs/content/guides/getting-started/tutorials/with-sveltekit.mdx@@ -85,13 +85,23 @@ export const handle: Handle = async ({ event, resolve }) => {})/**- * A convenience helper so we can just call await getSession() instead const { data: { session } } = await supabase.auth.getSession()+ * Unlike `supabase.auth.getSession`, which is unsafe on the server because it+ * doesn't validate the JWT, this function validates the JWT by first calling+ * `getUser` and aborts early if the JWT signature is invalid.*/- event.locals.getSession = async () => {+ event.locals.safeGetSession = async () => {+ const {+ data: { user },+ error,+ } = await supabase.auth.getUser()+ if (error) {+ return { session: null, user: null }+ }+const {data: { session },} = await event.locals.supabase.auth.getSession()- return session+ return { session, user }}return resolve(event, {@@ -104,9 +114,7 @@ export const handle: Handle = async ({ event, resolve }) => {<GetSessionWarning />-In this case, the session information from `getSession` is supplied to the Supabase client so it can retrieve the auth token. This is safe, since the auth token signature will be revalidated on the Auth server. But you shouldn't trust the unsigned data that is stored alongside the JWT.--If you are using TypeScript the compiler might complain about `event.locals.supabase` and `event.locals.getSession`, this can be fixed by updating your `src/app.d.ts` with the content below:+If you are using TypeScript the compiler might complain about `event.locals.supabase` and `event.locals.safeGetSession`, this can be fixed by updating your `src/app.d.ts` with the content below:```ts src/app.d.ts// src/app.d.ts@@ -117,10 +125,11 @@ declare global {namespace App {interface Locals {supabase: SupabaseClient- getSession(): Promise<Session | null>+ safeGetSession(): Promise<{ session: Session | null; user: User | null }>}interface PageData {session: Session | null+ user: User | null}// interface Error {}// interface Platform {}@@ -134,9 +143,12 @@ Create a new `src/routes/+layout.server.ts` file to handle the session on the se// src/routes/+layout.server.tsimport type { LayoutServerLoad } from './$types'-export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {+export const load: LayoutServerLoad = async ({ locals: { safeGetSession } }) => {+ const { session, user } = await safeGetSession()+return {- session: await getSession(),+ session,+ user,}}```@@ -170,6 +182,11 @@ 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`.+ */const {data: { session },} = await supabase.auth.getSession()@@ -259,8 +276,8 @@ Create a `src/routes/+page.server.ts` file that will return our website URL to bimport { redirect } from '@sveltejs/kit'import type { PageServerLoad } from './$types'-export const load: PageServerLoad = async ({ url, locals: { getSession } }) => {- const session = await getSession()+export const load: PageServerLoad = async ({ url, locals: { safeGetSession } }) => {+ const { session } = await safeGetSession()// if the user is already logged in return them to the account pageif (session) {@@ -419,8 +436,8 @@ and handle all our form actions through the `actions` object.import { fail, redirect } from '@sveltejs/kit'import type { Actions, PageServerLoad } from './$types'-export const load: PageServerLoad = async ({ locals: { supabase, getSession } }) => {- const session = await getSession()+export const load: PageServerLoad = async ({ locals: { supabase, safeGetSession } }) => {+ const { session } = await safeGetSession()if (!session) {throw redirect(303, '/')@@ -436,14 +453,14 @@ export const load: PageServerLoad = async ({ locals: { supabase, getSession } })}export const actions: Actions = {- update: async ({ request, locals: { supabase, getSession } }) => {+ update: async ({ request, locals: { supabase, safeGetSession } }) => {const formData = await request.formData()const fullName = formData.get('fullName') as stringconst username = formData.get('username') as stringconst website = formData.get('website') as stringconst avatarUrl = formData.get('avatarUrl') as string- const session = await getSession()+ const { session } = await safeGetSession()const { error } = await supabase.from('profiles').upsert({id: session?.user.id,@@ -470,8 +487,8 @@ export const actions: Actions = {avatarUrl,}},- signout: async ({ locals: { supabase, getSession } }) => {- const session = await getSession()+ signout: async ({ locals: { supabase, safeGetSession } }) => {+ const { session } = await safeGetSession()if (session) {await supabase.auth.signOut()throw redirect(303, '/')