Skip to content

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

docs: SSR overhaul combined client page PoC (#38405)

Chris Chinchilla534c300a7adb
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index a053d8a96a2..6c969cff86a 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -712,12 +712,6 @@ export const auth: NavMenuConstant = {
name: 'Server-Side Rendering',
url: '/guides/auth/server-side',
items: [
- { name: 'Overview', url: '/guides/auth/server-side' },
- { name: 'Next.js guide', url: '/guides/auth/server-side/nextjs' },
- {
- name: 'SvelteKit guide',
- url: '/guides/auth/server-side/sveltekit' as `/${string}`,
- },
{ name: 'Creating a client', url: '/guides/auth/server-side/creating-a-client' },
{
name: 'Migrating from Auth Helpers',
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 4440e53b0e8..0c98dbfda43 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
@@ -7,14 +7,14 @@ To use Server-Side Rendering (SSR) with Supabase, you need to configure your Sup
## Install
-Install the `@supabase/ssr` and `@supabase/supabase-js` packages:
+Install the `@supabase/supabase-js` and `@supabase/ssr` helper packages:
<Tabs size="small" type="underlined" queryGroup="package-manager" defaultActiveId="npm">
<TabPanel id="npm" label="npm">
```bash
-npm install @supabase/ssr @supabase/supabase-js
+npm install @supabase/supabase-js @supabase/ssr
```
</TabPanel>
@@ -22,7 +22,7 @@ npm install @supabase/ssr @supabase/supabase-js
<TabPanel id="yarn" label="yarn">
```bash
-yarn add @supabase/ssr @supabase/supabase-js
+yarn add @supabase/supabase-js @supabase/ssr
```
</TabPanel>
@@ -30,7 +30,7 @@ yarn add @supabase/ssr @supabase/supabase-js
<TabPanel id="pnpm" label="pnpm">
```bash
-pnpm add @supabase/ssr @supabase/supabase-js
+pnpm add @supabase/supabase-js @supabase/ssr
```
</TabPanel>
@@ -39,7 +39,7 @@ pnpm add @supabase/ssr @supabase/supabase-js
## Set environment variables
-In your environment variables file, set your Supabase URL and Key:
+Create a `.env.local` file in the project root directory. In the file, set the project's Supabase URL and Key:
<ProjectConfigVariables variable="url" />
<ProjectConfigVariables variable="publishable" />
@@ -50,48 +50,48 @@ In your environment variables file, set your Supabase URL and Key:
<TabPanel id="nextjs" label="Next.js">
```bash .env.local
-NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url
-NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
+NEXT_PUBLIC_SUPABASE_URL=supabase_project_url
+NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
</TabPanel>
<TabPanel id="sveltekit" label="SvelteKit">
```bash .env.local
-PUBLIC_SUPABASE_URL=your_supabase_project_url
-PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
+PUBLIC_SUPABASE_URL=supabase_project_url
+PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
</TabPanel>
<TabPanel id="astro" label="Astro">
```bash .env
-PUBLIC_SUPABASE_URL=your_supabase_project_url
-PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
+PUBLIC_SUPABASE_URL=supabase_project_url
+PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
</TabPanel>
<TabPanel id="remix" label="Remix">
```bash .env
-SUPABASE_URL=your_supabase_project_url
-SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
+SUPABASE_URL=supabase_project_url
+SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
</TabPanel>
<TabPanel id="react-router" label="React Router">
```bash .env
-SUPABASE_URL=your_supabase_project_url
-SUPABASE_ANON_KEY=your_supabase_anon_key
+SUPABASE_URL=supabase_project_url
+SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
</TabPanel>
<TabPanel id="express" label="Express">
```bash .env
-SUPABASE_URL=your_supabase_project_url
-SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
+SUPABASE_URL=supabase_project_url
+SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
Install [dotenv](https://www.npmjs.com/package/dotenv):
@@ -134,8 +134,8 @@ pnpm add dotenv
<TabPanel id="hono" label="Hono">
```bash .env
-SUPABASE_URL=your_supabase_project_url
-SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
+SUPABASE_URL=supabase_project_url
+SUPABASE_PUBLISHABLE_KEY=supabase_publishable_key
```
</TabPanel>
@@ -143,7 +143,8 @@ SUPABASE_PUBLISHABLE_KEY=sb_publishable_... or anon keyY
## Create a client
-You'll need some one-time setup code to configure your Supabase client to use cookies. Once your utility code is set up, you can use your new `createClient` utility functions to get a properly configured Supabase client.
+{/* TODO: Can this be consolidated? */}
+You need setup code to configure a Supabase client to use cookies. Once you have the utility code, you can use the `createClient` utility functions to get a properly configured Supabase client.
Use the browser client in code that runs on the browser, and the server client in code that runs on the server.
@@ -156,297 +157,162 @@ Use the browser client in code that runs on the browser, and the server client i
>
<TabPanel id="nextjs" label="Next.js">
-The following code samples are for App Router. For help with Pages Router, see the [Next.js Server-Side Auth guide](/docs/guides/auth/server-side/nextjs?queryGroups=router&router=pages).
+### Write utility functions to create Supabase clients
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="client-component"
- queryGroup="environment"
->
-<TabPanel id="client" label="Client-side">
+To access Supabase from a Next.js app, you need 2 types of Supabase clients:
-```ts utils/supabase/client.ts
-import { createBrowserClient } from '@supabase/ssr'
+1. **Client Component client** - To access Supabase from Client Components, which run in the browser.
+2. **Server Component client** - To access Supabase from Server Components, Server Actions, and Route Handlers, which run only on the server.
-export function createClient() {
- return createBrowserClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
- )
-}
-```
+Since Next.js Server Components can't write cookies, you need middleware to refresh expired Auth tokens and store them.
-</TabPanel>
+The middleware is responsible for:
-<TabPanel id="server" label="Server-side">
+1. Refreshing the Auth token by calling `supabase.auth.getClaims()`.
+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`.
-```ts utils/supabase/server.ts
-import { createServerClient } from '@supabase/ssr'
-import { cookies } from 'next/headers'
+<Accordion>
-export async function createClient() {
- const cookieStore = await cookies()
+ <AccordionItem
+ header={<span className="text-foreground">What does the `cookies` object do?</span>}
+ id="utility-cookies"
+ >
- return createServerClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
- {
- cookies: {
- getAll() {
- return cookieStore.getAll()
- },
- setAll(cookiesToSet) {
- try {
- cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options)
- )
- } catch {
- // The `setAll` method was called from a Server Component.
- // This can be ignored if you have middleware refreshing
- // user sessions.
- }
- },
- },
- }
- )
-}
-```
+ The cookies object lets the Supabase client know how to access the cookies, so it can read and write the user session data. To make `@supabase/ssr` framework-agnostic, the cookies methods aren't hard-coded. These utility functions adapt `@supabase/ssr`'s cookie handling for Next.js.
-</TabPanel>
+ The `set` and `remove` methods for the server client need error handlers, because Next.js throws an error if cookies are set from Server Components. You can safely ignore this error because you'll set up middleware in the next step to write refreshed cookies to storage.
-<TabPanel id="middleware" label="Middleware">
+ The cookie is named `sb-<project_ref>-auth-token` by default.
-In Next.js, because Server Components cannot set cookies, you'll also need a middleware client to handle cookie refreshes. The middleware should run before every route that needs access to Supabase, or that is protected by Supabase Auth.
+ </AccordionItem>
-```ts middleware.ts
-import { type NextRequest } from 'next/server'
-import { updateSession } from '@/utils/supabase/middleware'
+ <AccordionItem
+ header={<span className="text-foreground">Do I need to create a new client for every route?</span>}
+ id="client-deduplication"
+ >
-export async function middleware(request: NextRequest) {
- return await updateSession(request)
-}
+ Yes! Creating a Supabase client is lightweight.
-export const config = {
- matcher: [
- /*
- * Match all request paths except for the ones starting with:
- * - _next/static (static files)
- * - _next/image (image optimization files)
- * - favicon.ico (favicon file)
- * Feel free to modify this pattern to include more paths.
- */
- '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
- ],
-}
-```
+ - On the server, it basically configures a `fetch` call. You need to reconfigure the fetch call anew for every request to your server, because you need the cookies from the request.
+ - On the client, `createBrowserClient` already uses a singleton pattern, so you only ever create one instance, no matter how many times you call your `createClient` function.
-```ts utils/supabase/middleware.ts
-import { createServerClient } from '@supabase/ssr'
-import { NextResponse, type NextRequest } from 'next/server'
+ </AccordionItem>
-export async function updateSession(request: NextRequest) {
- let supabaseResponse = NextResponse.next({
- request,
- })
+</Accordion>
- const supabase = createServerClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
- {
- cookies: {
- getAll() {
- return request.cookies.getAll()
- },
- setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
- supabaseResponse = NextResponse.next({
- request,
- })
- cookiesToSet.forEach(({ name, value, options }) =>
- supabaseResponse.cookies.set(name, value, options)
- )
- },
- },
- }
- )
+Create a `utils/supabase` folder at the root of your project, or inside the `./src` folder if you are using one, with a file for each type of client. Then copy the utility functions for each client type.
- // IMPORTANT: Avoid writing any logic between createServerClient and
- // supabase.auth.getClaims(). A simple mistake could make it very hard to debug
- // issues with users being randomly logged out.
+<div className="mt-12">
+ <$CodeTabs>
+ <$CodeSample
+ path="/auth/nextjs/utils/supabase/client.ts"
+ meta="name=utils/supabase/client.ts"
+ language="typescript"
+ />
+ <$CodeSample
+ path="/auth/nextjs/utils/supabase/server.ts"
+ meta="name=utils/supabase/server.ts"
+ language="typescript"
+ />
+ </$CodeTabs>
+</div>
- // IMPORTANT: Don't remove getClaims()
- const { data } = await supabase.auth.getClaims()
+### Hook up middleware
- const user = data?.claims
+The code adds a [matcher](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths) so the middleware doesn't run on routes that don't access Supabase.
- if (
- !user &&
- !request.nextUrl.pathname.startsWith('/login') &&
- !request.nextUrl.pathname.startsWith('/auth')
- ) {
- // no user, potentially respond by redirecting the user to the login page
- const url = request.nextUrl.clone()
- url.pathname = '/login'
- return NextResponse.redirect(url)
- }
+<Admonition type="danger">
- // IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
- // creating a new response object with NextResponse.next() make sure to:
- // 1. Pass the request in it, like so:
- // const myNewResponse = NextResponse.next({ request })
- // 2. Copy over the cookies, like so:
- // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
- // 3. Change the myNewResponse object to fit your needs, but avoid changing
- // the cookies!
- // 4. Finally:
- // return myNewResponse
- // If this is not done, you may be causing the browser and server to go out
- // of sync and terminate the user's session prematurely!
-
- return supabaseResponse
-}
-```
+Be careful when protecting pages. The server gets the user session from the cookies, which can be spoofed by anyone.
-</TabPanel>
-</Tabs>
+Always use `supabase.auth.getClaims()` to protect pages and user data.
-</TabPanel>
-<TabPanel id="sveltekit" label="SvelteKit">
+_Never_ trust `supabase.auth.getSession()` inside server code such as middleware. It isn't guaranteed to revalidate the Auth token.
-<Tabs
- scrollable
- size="small"
- type="underlined"
- defaultActiveId="hooks"
- queryGroup="environment"
->
-<TabPanel id="hooks" label="Hooks">
+It's safe to trust `getClaims()` because it validates the JWT signature against the project's published public keys every time.
-```ts hooks.server.ts
-import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY } from '$env/static/public'
-import { createServerClient } from '@supabase/ssr'
-import type { Handle } from '@sveltejs/kit'
+</Admonition>
-export const handle: Handle = async ({ event, resolve }) => {
- event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
- cookies: {
- getAll() {
- return event.cookies.getAll()
- },
- setAll(cookiesToSet) {
- /**
- * 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
- * will replicate previous/standard behavior (https://kit.svelte.dev/docs/types#public-types-cookies)
- */
- cookiesToSet.forEach(({ name, value, options }) =>
- event.cookies.set(name, value, { ...options, path: '/' })
- )
- },
- },
- })
+<div className="mt-12">
+ <$CodeTabs>
+ <$CodeSample
+ path="/auth/nextjs/middleware.ts"
+ meta="name=middleware.ts"
+ language="typescript"
+ />
+ <$CodeSample
+ path="/auth/nextjs/utils/supabase/middleware.ts"
+ meta="name=utils/supabase/middleware.ts"
+ language="typescript"
+ />
+ </$CodeTabs>
+</div>
- /**
- * 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 }
- }
+## Congratulations
- const {
- data: { user },
- error,
- } = await event.locals.supabase.auth.getUser()
- if (error) {
- // JWT validation has failed
- return { session: null, user: null }
- }
+You're done! To recap, you've successfully:
- return { session, user }
- }
+- Called Supabase from a Server Action.
+- Called Supabase from a Server Component.
+- Set up a Supabase client utility to call Supabase from a Client Component. You can use this if you need to call Supabase from a Client Component, for example to set up a realtime subscription.
+- Set up middleware to automatically refresh the Supabase Auth session.
- return resolve(event, {
- filterSerializedResponseHeaders(name) {
- return name === 'content-range' || name === 'x-supabase-api-version'
- },
- })
-}
-```
+You can now use any Supabase features from your client or server code!
</TabPanel>
+<TabPanel id="sveltekit" label="SvelteKit">
-<TabPanel id="layout" label="Root Layout Load">
+### Set up server-side hooks
-Page components can get access to the Supabase client from the `data` object due to this load function.
+Set up server-side hooks in `src/hooks.server.ts`. The hooks:
-```ts +layout.ts
-import { PUBLIC_SUPABASE_PUBLISHABLE_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'
-import type { LayoutLoad } from './$types'
-import { createBrowserClient, createServerClient, isBrowser } from '@supabase/ssr'
+- Create a request-specific Supabase client, using the user credentials from the request cookie. This client is used for server-only code.
+- Check user authentication.
+- Guard protected pages.
-export const load: LayoutLoad = async ({ fetch, data, depends }) => {
- depends('supabase:auth')
+<$CodeSample
+path="/auth/sveltekit/src/hooks.server.ts"
+meta="name=src/hooks.server.ts"
+language="typescript"
+/>
- const supabase = isBrowser()
- ? createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
- global: {
- fetch,
- },
- })
- : createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
- global: {
- fetch,
- },
- cookies: {
- getAll() {
- return data.cookies
- },
- },
- })
-
- /**
- * 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()
-
- return { supabase, session }
-}
-```
+To prevent TypeScript errors, add type definitions for the new event.locals properties.
-</TabPanel>
+<$CodeSample
+path="/auth/sveltekit/src/app.d.ts"
+meta="name=src/app.d.ts"
+language="typescript"
+/>
-<TabPanel id="layout-server" label="Root Server Layout">
+### Create a Supabase client in your root layout
-```ts +layout.server.ts
-import type { LayoutServerLoad } from './$types'
+Create a Supabase client in your root `+layout.ts`. This client can be used to access Supabase from the client or the server. In order to get access to the Auth token on the server, use a `+layout.server.ts` file to pass in the session from event.locals.
-export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
- const { session, user } = await safeGetSession()
+Page components can access the Supabase client from the `data` object using the `load` function.
- return {
- session,
- user,
- cookies: cookies.getAll(),
- }
-}
-```
+<$CodeTabs>
+<$CodeSample
+path="/auth/sveltekit/src/routes/+layout.ts"
+meta="name=src/routes/+layout.ts"
+language="typescript"
+/>
-</TabPanel>
+<$CodeSample
+path="/auth/sveltekit/src/routes/+layout.server.ts"
+meta="name=src/routes/+layout.server.ts"
+language="typescript"
+/>
+</$CodeTabs>
-</Tabs>
+## Congratulations
+
+You're done! To recap, you've successfully:
+
+- Set up server-side hooks to create a request-specific Supabase client and guard protected pages.
+- Created a Supabase client in your root layout to use on both the client and server.
+
+You can now use any Supabase features from your client or server code!
</TabPanel>
<TabPanel id="astro" label="Astro">
@@ -483,8 +349,8 @@ const supabase = createServerClient(
return parseCookieHeader(Astro.request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- Astro.cookies.set(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ Astro.cookies.set(name, value))
},
},
}
@@ -525,8 +391,8 @@ export async function GET(context: APIContext) {
return parseCookieHeader(context.request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- context.cookies.set(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ context.cookies.set(name, value))
},
},
}
@@ -554,9 +420,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
return parseCookieHeader(context.request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- context.cookies.set(name, value, options)
- )
+ cookiesToSet.forEach(({ name, value }) => context.cookies.set(name, value))
},
},
}
@@ -569,6 +433,10 @@ export const onRequest = defineMiddleware(async (context, next) => {
</TabPanel>
</Tabs>
+## Congratulations
+
+You can now use any Supabase features from your client or server code!
+
</TabPanel>
<TabPanel id="remix" label="Remix">
@@ -597,8 +465,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- headers.append('Set-Cookie', serializeCookieHeader(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ headers.append('Set-Cookie', serializeCookieHeader(name, value))
)
},
},
@@ -631,8 +499,8 @@ export async function action({ request }: ActionFunctionArgs) {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- headers.append('Set-Cookie', serializeCookieHeader(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ headers.append('Set-Cookie', serializeCookieHeader(name, value))
)
},
},
@@ -675,6 +543,10 @@ export default function Index() {
</TabPanel>
</Tabs>
+## Congratulations
+
+You can now use any Supabase features from your client or server code!
+
</TabPanel>
<TabPanel id="react-router" label="React Router">
@@ -701,8 +573,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- headers.append('Set-Cookie', serializeCookieHeader(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ headers.append('Set-Cookie', serializeCookieHeader(name, value))
)
},
},
@@ -731,8 +603,8 @@ export async function action({ request }: ActionFunctionArgs) {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- headers.append('Set-Cookie', serializeCookieHeader(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ headers.append('Set-Cookie', serializeCookieHeader(name, value))
)
},
},
@@ -774,6 +646,10 @@ export default function Index() {
</TabPanel>
</Tabs>
+## Congratulations
+
+You can now use any Supabase features from your client or server code!
+
</TabPanel>
<TabPanel id="express" label="Express">
@@ -797,8 +673,8 @@ exports.createClient = (context) => {
return parseCookieHeader(context.req.headers.cookie ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- context.res.appendHeader('Set-Cookie', serializeCookieHeader(name, value, options))
+ cookiesToSet.forEach(({ name, value }) =>
+ context.res.appendHeader('Set-Cookie', serializeCookieHeader(name, value))
)
},
},
@@ -828,6 +704,10 @@ app.post("/hello-world", async function (req, res, next) {
</TabPanel>
</Tabs>
+## Congratulations
+
+You can now use any Supabase features from your client or server code!
+
</TabPanel>
<TabPanel id="hono" label="Hono">
@@ -843,107 +723,22 @@ app.post("/hello-world", async function (req, res, next) {
Create a Hono middleware that creates a Supabase client.
-```ts middleware/auth.middleware.ts
-import { createServerClient, parseCookieHeader } from '@supabase/ssr'
-import { SupabaseClient } from '@supabase/supabase-js'
-import type { Context, MiddlewareHandler } from 'hono'
-import { env } from 'hono/adapter'
-import { setCookie } from 'hono/cookie'
-
-declare module 'hono' {
- interface ContextVariableMap {
- supabase: SupabaseClient
- }
-}
-
-export const getSupabase = (c: Context) => {
- return c.get('supabase')
-}
-
-type SupabaseEnv = {
- SUPABASE_URL: string
- SUPABASE_PUBLISHABLE_KEY: string
-}
-
-export const supabaseMiddleware = (): MiddlewareHandler => {
- return async (c, next) => {
- const supabaseEnv = env<SupabaseEnv>(c)
- const supabaseUrl = supabaseEnv.SUPABASE_URL
- const supabaseAnonKey = supabaseEnv.SUPABASE_PUBLISHABLE_KEY
-
- if (!supabaseUrl) {
- throw new Error('SUPABASE_URL missing!')
- }
-
- if (!supabaseAnonKey) {
- throw new Error('SUPABASE_PUBLISHABLE_KEY missing!')
- }
-
- const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
- cookies: {
- getAll() {
- return parseCookieHeader(c.req.header('Cookie') ?? '')
- },
- setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) => setCookie(c, name, value, options))
- },
- },
- })
-
- c.set('supabase', supabase)
-
- await next()
- }
-}
-```
+<$CodeSample
+path="/auth/hono/src/middleware/auth.middleware.ts"
+meta="name=src/middleware/auth.middleware.ts"
+language="typescript"
+/>
</TabPanel>
<TabPanel id="hono-route" label="Route">
You can now use this middleware in your Hono application to create a server Supabase client that can be used to make authenticated requests.
-```ts index.tsx
-import { Hono } from 'hono'
-import { getSupabase, supabaseMiddleware } from './middleware/auth.middleware'
-
-const app = new Hono()
-app.use('*', supabaseMiddleware())
-
-app.get('/api/user', async (c) => {
- const supabase = getSupabase(c)
- const { data, error } = await supabase.auth.getUser()
-
- if (error) console.log('error', error)
-
- if (!data?.user) {
- return c.json({
- message: 'You are not logged in.',
- })
- }
-
- return c.json({
- message: 'You are logged in!',
- userId: data.user,
- })
-})
-
-app.get('/signout', async (c) => {
- const supabase = getSupabase(c)
- await supabase.auth.signOut()
- console.log('Signed out server-side!')
- return c.redirect('/')
-})
-
-// Retrieve data with RLS enabled. The signed in user's auth token is automatically sent.
-app.get('/countries', async (c) => {
- const supabase = getSupabase(c)
- const { data, error } = await supabase.from('countries').select('*')
- if (error) console.log(error)
- return c.json(data)
-})
-
-export default app
-```
+<$CodeSample
+path="/auth/hono/src/index.tsx"
+meta="name=src/index.tsx"
+language="typescript"
+/>
</TabPanel>
</Tabs>
diff --git a/apps/docs/content/guides/auth/server-side/nextjs.mdx b/apps/docs/content/guides/auth/server-side/nextjs.mdx
deleted file mode 100644
index 5e0d03e78b4..00000000000
--- a/apps/docs/content/guides/auth/server-side/nextjs.mdx
+++ /dev/null
@@ -1,1012 +0,0 @@
----
-title: 'Setting up Server-Side Auth for Next.js'
-sidebar_label: 'Next.js guide'
-hideToc: true
----
-
-Next.js comes in two flavors: the [App Router](https://nextjs.org/docs/app) and the [Pages Router](https://nextjs.org/docs/pages). You can set up Server-Side Auth with either strategy. You can even use both in the same application.
-
-<Tabs scrollable size="small" type="underlined" defaultActiveId="app" queryGroup="router">
-
-<TabPanel id="app" label="App Router">
-
-<StepHikeCompact>
-
-<StepHikeCompact.Step step={1}>
-
-<StepHikeCompact.Details title="Install Supabase packages">
-
-Install the `@supabase/supabase-js` package and the helper `@supabase/ssr` package.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-```sh
-npm install @supabase/supabase-js @supabase/ssr
-```
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={2}>
-
-<StepHikeCompact.Details title="Set up environment variables">
-
-Create a `.env.local` file in your project root directory.
-
-Fill in your `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`:
-
-<ProjectConfigVariables variable="url" />
-<ProjectConfigVariables variable="publishable" />
-<ProjectConfigVariables variable="anon" />
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```txt name=.env.local
-NEXT_PUBLIC_SUPABASE_URL=<your_supabase_project_url>
-NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=<sb_publishable_... or anon keyY>
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={3}>
-
-<StepHikeCompact.Details title="Write utility functions to create Supabase clients">
-
-To access Supabase from your Next.js app, you need 2 types of Supabase clients:
-
-1. **Client Component client** - To access Supabase from Client Components, which run in the browser.
-1. **Server Component client** - To access Supabase from Server Components, Server Actions, and Route Handlers, which run only on the server.
-
-Create a `utils/supabase` folder at the root of your project, or inside the `./src` folder if you are using one, with a file for each type of client. Then copy the utility functions for each client type.
-
-<Accordion
- type="default"
- openBehaviour="multiple"
- chevronAlign="right"
- justified
- size="medium"
- className="text-foreground-light mt-8 mb-6"
->
- <div className="border-b mt-3 pb-3">
- <AccordionItem
- header={<span className="text-foreground">What does the `cookies` object do?</span>}
- id="utility-cookies"
- >
-
- The cookies object lets the Supabase client know how to access the cookies, so it can read and write the user session data. To make `@supabase/ssr` framework-agnostic, the cookies methods aren't hard-coded. These utility functions adapt `@supabase/ssr`'s cookie handling for Next.js.
-
- The `set` and `remove` methods for the server client need error handlers, because Next.js throws an error if cookies are set from Server Components. You can safely ignore this error because you'll set up middleware in the next step to write refreshed cookies to storage.
-
- The cookie is named `sb-<project_ref>-auth-token` by default.
-
- </AccordionItem>
-
- </div>
- <div className="border-b mt-3 pb-3">
- <AccordionItem
- header={<span className="text-foreground">Do I need to create a new client for every route?</span>}
- id="client-deduplication"
- >
-
- Yes! Creating a Supabase client is lightweight.
-
- - On the server, it basically configures a `fetch` call. You need to reconfigure the fetch call anew for every request to your server, because you need the cookies from the request.
- - On the client, `createBrowserClient` already uses a singleton pattern, so you only ever create one instance, no matter how many times you call your `createClient` function.
-
- </AccordionItem>
-
- </div>
-</Accordion>
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=utils/supabase/client.ts
-import { createBrowserClient } from '@supabase/ssr'
-
-export function createClient() {
- return createBrowserClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
- )
-}
-```
-
-```ts name=utils/supabase/server.ts
-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() {
- return cookieStore.getAll()
- },
- setAll(cookiesToSet) {
- try {
- cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options)
- )
- } catch {
- // The `setAll` method was called from a Server Component.
- // This can be ignored if you have middleware refreshing
- // user sessions.
- }
- },
- },
- }
- )
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={4}>
-
-<StepHikeCompact.Details title="Hook up middleware">
-
-Create a `middleware.ts` file at the root of your project, or inside the `./src` folder if you are using one.
-
-Since Server Components can't write cookies, you need middleware to refresh expired Auth tokens and store them.
-
-The middleware is responsible for:
-
-1. Refreshing the Auth token (by calling `supabase.auth.getUser`).
-1. 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`.
-1. Passing the refreshed Auth token to the browser, so it replaces the old token. This is accomplished with `response.cookies.set`.
-
-Copy the middleware code for your app.
-
-Add a [matcher](https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths) so the middleware doesn't run on routes that don't access Supabase.
-
-<Admonition type="danger">
-
-Be careful when protecting pages. The server gets the user session from the cookies, which can be spoofed by anyone.
-
-Always use `supabase.auth.getUser()` to protect pages and user data.
-
-_Never_ trust `supabase.auth.getSession()` inside server code such as middleware. It isn't guaranteed to revalidate the Auth token.
-
-It's safe to trust `getUser()` because it sends a request to the Supabase Auth server every time to revalidate the Auth token.
-
-</Admonition>
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=middleware.ts
-import { type NextRequest } from 'next/server'
-import { updateSession } from '@/utils/supabase/middleware'
-
-export async function middleware(request: NextRequest) {
- return await updateSession(request)
-}
-
-export const config = {
- matcher: [
- /*
- * Match all request paths except for the ones starting with:
- * - _next/static (static files)
- * - _next/image (image optimization files)
- * - favicon.ico (favicon file)
- * Feel free to modify this pattern to include more paths.
- */
- '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
- ],
-}
-```
-
-```ts name=utils/supabase/middleware.ts
-import { createServerClient } from '@supabase/ssr'
-import { NextResponse, type NextRequest } from 'next/server'
-
-export async function updateSession(request: NextRequest) {
- let supabaseResponse = NextResponse.next({
- request,
- })
-
- const supabase = createServerClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
- {
- cookies: {
- getAll() {
- return request.cookies.getAll()
- },
- setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
- supabaseResponse = NextResponse.next({
- request,
- })
- cookiesToSet.forEach(({ name, value, options }) =>
- supabaseResponse.cookies.set(name, value, options)
- )
- },
- },
- }
- )
-
- // Do not run code between createServerClient and
- // supabase.auth.getUser(). A simple mistake could make it very hard to debug
- // issues with users being randomly logged out.
-
- // IMPORTANT: DO NOT REMOVE auth.getUser()
-
- const {
- data: { user },
- } = await supabase.auth.getUser()
-
- if (
- !user &&
- !request.nextUrl.pathname.startsWith('/login') &&
- !request.nextUrl.pathname.startsWith('/auth') &&
- !request.nextUrl.pathname.startsWith('/error')
- ) {
- // no user, potentially respond by redirecting the user to the login page
- const url = request.nextUrl.clone()
- url.pathname = '/login'
- return NextResponse.redirect(url)
- }
-
- // IMPORTANT: You *must* return the supabaseResponse object as it is.
- // If you're creating a new response object with NextResponse.next() make sure to:
- // 1. Pass the request in it, like so:
- // const myNewResponse = NextResponse.next({ request })
- // 2. Copy over the cookies, like so:
- // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
- // 3. Change the myNewResponse object to fit your needs, but avoid changing
- // the cookies!
- // 4. Finally:
- // return myNewResponse
- // If this is not done, you may be causing the browser and server to go out
- // of sync and terminate the user's session prematurely!
-
- return supabaseResponse
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={5}>
-
-<StepHikeCompact.Details title="Create a login page">
-
-Create a login page for your app. Use a Server Action to call the Supabase signup function.
-
-Since Supabase is being called from an Action, use the client defined in `@/utils/supabase/server.ts`.
-
-<Admonition type="note">
-
-Note that `cookies` is called before any calls to Supabase, which opts fetch calls out of Next.js's caching. This is important for authenticated data fetches, to ensure that users get access only to their own data.
-
-See the Next.js docs to learn more about [opting out of data caching](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching).
-
-</Admonition>
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=app/login/page.tsx
-import { login, signup } from './actions'
-
-export default function LoginPage() {
- return (
- <form>
- <label htmlFor="email">Email:</label>
- <input id="email" name="email" type="email" required />
- <label htmlFor="password">Password:</label>
- <input id="password" name="password" type="password" required />
- <button formAction={login}>Log in</button>
- <button formAction={signup}>Sign up</button>
- </form>
- )
-}
-```
-
-```ts name=app/login/actions.ts
-'use server'
-
-import { revalidatePath } from 'next/cache'
-import { redirect } from 'next/navigation'
-
-import { createClient } from '@/utils/supabase/server'
-
-export async function login(formData: FormData) {
- const supabase = await createClient()
-
- // type-casting here for convenience
- // in practice, you should validate your inputs
- const data = {
- email: formData.get('email') as string,
- password: formData.get('password') as string,
- }
-
- const { error } = await supabase.auth.signInWithPassword(data)
-
- if (error) {
- redirect('/error')
- }
-
- revalidatePath('/', 'layout')
- redirect('/')
-}
-
-export async function signup(formData: FormData) {
- const supabase = await createClient()
-
- // type-casting here for convenience
- // in practice, you should validate your inputs
- const data = {
- email: formData.get('email') as string,
- password: formData.get('password') as string,
- }
-
- const { error } = await supabase.auth.signUp(data)
-
- if (error) {
- redirect('/error')
- }
-
- revalidatePath('/', 'layout')
- redirect('/')
-}
-```
-
-```ts name=app/error/page.tsx
-'use client'
-
-export default function ErrorPage() {
- return <p>Sorry, something went wrong</p>
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={6}>
-
-<StepHikeCompact.Details title="Change the Auth confirmation path">
-
-If you have email confirmation turned on (the default), a new user will receive an email confirmation after signing up.
-
-Change the email template to support a server-side authentication flow.
-
-Go to the [Auth templates](/dashboard/project/_/auth/templates) page in your dashboard. In the `Confirm signup` template, change `{{ .ConfirmationURL }}` to `{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email`.
-
-</StepHikeCompact.Details>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={7}>
-
-<StepHikeCompact.Details title="Create a route handler for Auth confirmation">
-
-Create a Route Handler for `auth/confirm`. When a user clicks their confirmation email link, exchange their secure code for an Auth token.
-
-Since this is a Router Handler, use the Supabase client from `@/utils/supabase/server.ts`.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=app/auth/confirm/route.ts
-import { type EmailOtpType } from '@supabase/supabase-js'
-import { type NextRequest } from 'next/server'
-
-import { createClient } from '@/utils/supabase/server'
-import { redirect } from 'next/navigation'
-
-export async function GET(request: NextRequest) {
- const { searchParams } = new URL(request.url)
- const token_hash = searchParams.get('token_hash')
- const type = searchParams.get('type') as EmailOtpType | null
- const next = searchParams.get('next') ?? '/'
-
- if (token_hash && type) {
- const supabase = await createClient()
-
- const { error } = await supabase.auth.verifyOtp({
- type,
- token_hash,
- })
- if (!error) {
- // redirect user to specified redirect URL or root of app
- redirect(next)
- }
- }
-
- // redirect the user to an error page with some instructions
- redirect('/error')
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={8}>
-
-<StepHikeCompact.Details title="Access user info from Server Component">
-
-Server Components can read cookies, so you can get the Auth status and user info.
-
-Since you're calling Supabase from a Server Component, use the client created in `@/utils/supabase/server.ts`.
-
-Create a `private` page that users can only access if they're logged in. The page displays their email.
-
-<Admonition type="danger">
-
-Be careful when protecting pages. The server gets the user session from the cookies, which can be spoofed by anyone.
-
-Always use `supabase.auth.getUser()` to protect pages and user data.
-
-_Never_ trust `supabase.auth.getSession()` inside Server Components. It isn't guaranteed to revalidate the Auth token.
-
-It's safe to trust `getUser()` because it sends a request to the Supabase Auth server every time to revalidate the Auth token.
-
-</Admonition>
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=app/private/page.tsx
-import { redirect } from 'next/navigation'
-
-import { createClient } from '@/utils/supabase/server'
-
-export default async function PrivatePage() {
- const supabase = await createClient()
-
- const { data, error } = await supabase.auth.getUser()
- if (error || !data?.user) {
- redirect('/login')
- }
-
- return <p>Hello {data.user.email}</p>
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-</StepHikeCompact>
-
-## Congratulations
-
-You're done! To recap, you've successfully:
-
-- Called Supabase from a Server Action.
-- Called Supabase from a Server Component.
-- Set up a Supabase client utility to call Supabase from a Client Component. You can use this if you need to call Supabase from a Client Component, for example to set up a realtime subscription.
-- Set up middleware to automatically refresh the Supabase Auth session.
-
-You can now use any Supabase features from your client or server code!
-
-</TabPanel>
-
-<TabPanel id="pages" label="Pages Router">
-
-<StepHikeCompact>
-
-<StepHikeCompact.Step step={1}>
-
-<StepHikeCompact.Details title="Install Supabase packages">
-
-Install the `@supabase/supabase-js` package and the helper `@supabase/ssr` package.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-```sh
-npm install @supabase/supabase-js @supabase/ssr
-```
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={2}>
-
-<StepHikeCompact.Details title="Set up environment variables">
-
-Create a `.env.local` file in your project root directory.
-
-Fill in your `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`:
-
-<ProjectConfigVariables variable="url" />
-<ProjectConfigVariables variable="publishable" />
-<ProjectConfigVariables variable="anon" />
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-```txt name=.env.local
-NEXT_PUBLIC_SUPABASE_URL=<your_supabase_project_url>
-NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=<sb_publishable_... or anon keyY>
-```
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={3}>
-
-<StepHikeCompact.Details title="Write utility functions to create Supabase clients">
-
-To access Supabase from your Next.js app, you need 4 types of Supabase clients:
-
-1. **`getServerSideProps` client** - To access Supabase from `getServerSideProps`.
-1. **`getStaticProps` client** - To access Supabase from `getStaticProps`.
-1. **Component client** - To access Supabase from within components.
-1. **API route client** - To access Supabase from API route handlers.
-
-Create a `utils/supabase` folder with a file for each type of client. Then copy the utility functions for each client type.
-
-<Accordion
- type="default"
- openBehaviour="multiple"
- chevronAlign="right"
- justified
- size="medium"
- className="text-foreground-light mt-8 mb-6"
->
- <div className="border-b pb-3">
- <AccordionItem
- header={<span className="text-foreground">Why do I need so many types of clients?</span>}
- id="nextjs-clients"
- >
-
- A Supabase client reads and sets cookies in order to access and update the user session. Depending on where the client is used, it needs to interact with cookies in a different way:
-
- - **`getServerSideProps`** - Runs on the server. Reads cookies from the request, which is passed through from `GetServerSidePropsContext`.
- - **`getStaticProps`** - Runs at build time, where there is no user, session, or cookies.
- - **Component** - Runs on the client. Reads cookies from browser storage. Behind the scenes, `createBrowserClient` reuses the same client instance if called multiple times, so don't worry about deduplicating the client yourself.
- - **API route** - Runs on the server. Reads cookies from the request, which is passed through from `NextApiRequest`.
-
- </AccordionItem>
-
- </div>
- <div className="border-b mt-3 pb-3">
- <AccordionItem
- header={<span className="text-foreground">What does the `cookies` object do?</span>}
- id="client-storage-cookies"
- >
-
- The cookies object lets the Supabase client know how to access the cookies, so it can read and write the user session. To make `@supabase/ssr` framework-agnostic, the cookies methods aren't hard-coded. But you only need to set them up once. You can then reuse your utility functions whenever you need a Supabase client.
-
- The cookie is named `sb-<project_ref>-auth-token` by default.
-
- </AccordionItem>
-
- </div>
-</Accordion>
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=utils/supabase/server-props.ts
-import { type GetServerSidePropsContext } from 'next'
-import { createServerClient, serializeCookieHeader } from '@supabase/ssr'
-
-export function createClient({ req, res }: GetServerSidePropsContext) {
- const supabase = createServerClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
- {
- cookies: {
- getAll() {
- return Object.keys(req.cookies).map((name) => ({ name, value: req.cookies[name] || '' }))
- },
- setAll(cookiesToSet) {
- res.setHeader(
- 'Set-Cookie',
- cookiesToSet.map(({ name, value, options }) =>
- serializeCookieHeader(name, value, options)
- )
- )
- },
- },
- }
- )
-
- return supabase
-}
-```
-
-```ts name=utils/supabase/static-props.ts
-import { createClient as createClientPrimitive } from '@supabase/supabase-js'
-
-export function createClient() {
- const supabase = createClientPrimitive(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
- )
-
- return supabase
-}
-```
-
-```ts name=utils/supabase/component.ts
-import { createBrowserClient } from '@supabase/ssr'
-
-export function createClient() {
- const supabase = createBrowserClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
- )
-
- return supabase
-}
-```
-
-```ts name=utils/supabase/api.ts
-import { createServerClient, serializeCookieHeader } from '@supabase/ssr'
-import { type NextApiRequest, type NextApiResponse } from 'next'
-
-export default function createClient(req: NextApiRequest, res: NextApiResponse) {
- const supabase = createServerClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
- {
- cookies: {
- getAll() {
- return Object.keys(req.cookies).map((name) => ({ name, value: req.cookies[name] || '' }))
- },
- setAll(cookiesToSet) {
- res.setHeader(
- 'Set-Cookie',
- cookiesToSet.map(({ name, value, options }) =>
- serializeCookieHeader(name, value, options)
- )
- )
- },
- },
- }
- )
-
- return supabase
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={4}>
-
-<StepHikeCompact.Details title="Create a login page">
-
-Create a login page for your app.
-
-Since Supabase is being called from a component, use the client defined in `@/utils/supabase/component.ts`.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=pages/login.tsx
-import { useRouter } from 'next/router'
-import { useState } from 'react'
-
-import { createClient } from '@/utils/supabase/component'
-
-export default function LoginPage() {
- const router = useRouter()
- const supabase = createClient()
-
- const [email, setEmail] = useState('')
- const [password, setPassword] = useState('')
-
- async function logIn() {
- const { error } = await supabase.auth.signInWithPassword({ email, password })
- if (error) {
- console.error(error)
- }
- router.push('/')
- }
-
- async function signUp() {
- const { error } = await supabase.auth.signUp({ email, password })
- if (error) {
- console.error(error)
- }
- router.push('/')
- }
-
- return (
- <main>
- <form>
- <label htmlFor="email">Email:</label>
- <input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
- <label htmlFor="password">Password:</label>
- <input
- id="password"
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- />
- <button type="button" onClick={logIn}>
- Log in
- </button>
- <button type="button" onClick={signUp}>
- Sign up
- </button>
- </form>
- </main>
- )
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={5}>
-
-<StepHikeCompact.Details title="Change the Auth confirmation path">
-
-If you have email confirmation turned on (the default), a new user will receive an email confirmation after signing up.
-
-Change the email template to support a server-side authentication flow.
-
-Go to the [Auth templates](/dashboard/project/_/auth/templates) page in your dashboard. In the `Confirm signup` template, change `{{ .ConfirmationURL }}` to `{{ .SiteURL }}/api/auth/confirm?token_hash={{ .TokenHash }}&type=email`.
-
-</StepHikeCompact.Details>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={6}>
-
-<StepHikeCompact.Details title="Create a route handler for Auth confirmation">
-
-Create an API route for `api/auth/confirm`. When a user clicks their confirmation email link, exchange their secure code for an Auth token.
-
-Since this is an API route, use the Supabase client from `@/utils/supabase/api.ts`.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=pages/api/auth/confirm.ts
-import { type EmailOtpType } from '@supabase/supabase-js'
-import type { NextApiRequest, NextApiResponse } from 'next'
-
-import createClient from '@/utils/supabase/api'
-
-function stringOrFirstString(item: string | string[] | undefined) {
- return Array.isArray(item) ? item[0] : item
-}
-
-export default async function handler(req: NextApiRequest, res: NextApiResponse) {
- if (req.method !== 'GET') {
- res.status(405).appendHeader('Allow', 'GET').end()
- return
- }
-
- const queryParams = req.query
- const token_hash = stringOrFirstString(queryParams.token_hash)
- const type = stringOrFirstString(queryParams.type)
-
- let next = '/error'
-
- if (token_hash && type) {
- const supabase = createClient(req, res)
- const { error } = await supabase.auth.verifyOtp({
- type: type as EmailOtpType,
- token_hash,
- })
- if (error) {
- console.error(error)
- } else {
- next = stringOrFirstString(queryParams.next) || '/'
- }
- }
-
- res.redirect(next)
-}
-```
-
-```tsx name=pages/error.tsx
-export default function ErrorPage() {
- return <p>Sorry, something went wrong</p>
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={7}>
-
-<StepHikeCompact.Details title="Make an authenticated-only page using `getServerSideProps`">
-
-If you use dynamic server-side rendering, you can serve a page to authenticated users only by checking for the user data in `getServerSideProps`. Unauthenticated users will be redirected to the home page.
-
-Since you're calling Supabase from `getServerSideProps`, use the client from `@/utils/supabase/server-props.ts`.
-
-<Admonition type="danger">
-
-Be careful when protecting pages. The server gets the user session from the cookies, which can be spoofed by anyone.
-
-Always use `supabase.auth.getUser()` to protect pages and user data.
-
-_Never_ trust `supabase.auth.getSession()` inside server code. It isn't guaranteed to revalidate the Auth token.
-
-It's safe to trust `getUser()` because it sends a request to the Supabase Auth server every time to revalidate the Auth token.
-
-</Admonition>
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-```ts pages/private.tsx
-import type { User } from '@supabase/supabase-js'
-import type { GetServerSidePropsContext } from 'next'
-
-import { createClient } from '@/utils/supabase/server-props'
-
-export default function PrivatePage({ user }: { user: User }) {
- return <h1>Hello, {user.email || 'user'}!</h1>
-}
-
-export async function getServerSideProps(context: GetServerSidePropsContext) {
- const supabase = createClient(context)
-
- const { data, error } = await supabase.auth.getUser()
-
- if (error || !data) {
- return {
- redirect: {
- destination: '/',
- permanent: false,
- },
- }
- }
-
- return {
- props: {
- user: data.user,
- },
- }
-}
-```
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={8}>
-
-<StepHikeCompact.Details title="Fetch static data using `getStaticProps`">
-
-You can also fetch static data at build time using Supabase. Note that there's no session or user at build time, so the data will be the same for everyone who sees the page.
-
-Add some colors data to your database by running the [Colors Quickstart](/dashboard/project/_/sql/quickstarts) in the dashboard.
-
-Then fetch the colors data using `getStaticProps` with the client from `@/utils/supabase/static-props.ts`.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-```ts pages/public.tsx
-import { createClient } from '@/utils/supabase/static-props'
-
-export default function PublicPage({ data }: { data?: any[] }) {
- return <pre>{data && JSON.stringify(data, null, 2)}</pre>
-}
-
-export async function getStaticProps() {
- const supabase = createClient()
-
- const { data, error } = await supabase.from('colors').select()
-
- if (error || !data) {
- return { props: {} }
- }
-
- return { props: { data } }
-}
-```
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-</StepHikeCompact>
-
-## Congratulations
-
-You're done! To recap, you've successfully:
-
-- Called Supabase from a component
-- Called Supabase from an API route
-- Called Supabase from `getServerSideProps`
-- Called Supabase from `getStaticProps`
-
-You can now use any Supabase features from your client or server code!
-
-</TabPanel>
-
-<TabPanel id="hybrid" label="Hybrid router strategies">
-
-You can use both the App and Pages Routers together.
-
-Follow the instructions for both the App and Pages Routers. Whenever you need to connect to Supabase, import the `createClient` utility that you need:
-
-| Router | Code location | Which `createClient` to use |
-| ------------ | ------------------------------------------------- | --------------------------- |
-| App Router | Server Component, Server Action, or Route Handler | `server.ts` |
-| | Client Component | `client.ts` |
-| Pages Router | `getServerSideProps` | `server-props.ts` |
-| | `getStaticProps` | `static-props.ts` |
-| | Component | `component.ts` |
-| | API route | `api.ts` |
-
-Remember to create the `middleware.ts` file for the App Router so the session refreshes for App Router pages.
-
-</TabPanel>
-
-</Tabs>
diff --git a/apps/docs/content/guides/auth/server-side/sveltekit.mdx b/apps/docs/content/guides/auth/server-side/sveltekit.mdx
deleted file mode 100644
index e14fdf6aef9..00000000000
--- a/apps/docs/content/guides/auth/server-side/sveltekit.mdx
+++ /dev/null
@@ -1,648 +0,0 @@
----
-title: 'Setting up Server-Side Auth for SvelteKit'
-hideToc: true
----
-
-Set up Server-Side Auth to use cookie-based authentication with SvelteKit.
-
-<StepHikeCompact>
-
-<StepHikeCompact.Step step={1}>
-
-<StepHikeCompact.Details title="Install Supabase packages">
-
-Install the `@supabase/supabase-js` package and the helper `@supabase/ssr` package.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-```sh
-npm install @supabase/supabase-js @supabase/ssr
-```
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={2}>
-
-<StepHikeCompact.Details title="Set up environment variables">
-
-Create a `.env.local` file in your project root directory.
-
-Fill in your `PUBLIC_SUPABASE_URL` and `PUBLIC_SUPABASE_PUBLISHABLE_KEY`:
-
-<ProjectConfigVariables variable="url" />
-<ProjectConfigVariables variable="publishable" />
-<ProjectConfigVariables variable="anon" />
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```txt name=.env.local
-PUBLIC_SUPABASE_URL=<your_supabase_project_url>
-PUBLIC_SUPABASE_PUBLISHABLE_KEY=<sb_publishable_... or anon keyY>
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={3}>
-
-<StepHikeCompact.Details title="Set up server-side hooks">
-
-Set up server-side hooks in `src/hooks.server.ts`. The hooks:
-
-- Create a request-specific Supabase client, using the user credentials from the request cookie. This client is used for server-only code.
-- Check user authentication.
-- Guard protected pages.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/hooks.server.ts
-import { createServerClient } from '@supabase/ssr'
-import { type Handle, redirect } from '@sveltejs/kit'
-import { sequence } from '@sveltejs/kit/hooks'
-
-import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY } from '$env/static/public'
-
-const supabase: Handle = async ({ event, resolve }) => {
- /**
- * Creates a Supabase client specific to this server request.
- *
- * The Supabase client gets the Auth token from the request cookies.
- */
- event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
- cookies: {
- getAll: () => event.cookies.getAll(),
- /**
- * SvelteKit's cookies API requires `path` to be explicitly set in
- * the cookie options. Setting `path` to `/` replicates previous/
- * standard behavior.
- */
- setAll: (cookiesToSet) => {
- cookiesToSet.forEach(({ name, value, options }) => {
- event.cookies.set(name, value, { ...options, path: '/' })
- })
- },
- },
- })
-
- /**
- * 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) {
- /**
- * Supabase libraries use the `content-range` and `x-supabase-api-version`
- * headers, so we need to tell SvelteKit to pass it through.
- */
- return name === 'content-range' || name === 'x-supabase-api-version'
- },
- })
-}
-
-const authGuard: Handle = async ({ event, resolve }) => {
- const { session, user } = await event.locals.safeGetSession()
- event.locals.session = session
- event.locals.user = user
-
- if (!event.locals.session && event.url.pathname.startsWith('/private')) {
- redirect(303, '/auth')
- }
-
- if (event.locals.session && event.url.pathname === '/auth') {
- redirect(303, '/private')
- }
-
- return resolve(event)
-}
-
-export const handle: Handle = sequence(supabase, authGuard)
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={4}>
-
-<StepHikeCompact.Details title="Create TypeScript definitions">
-
-To prevent TypeScript errors, add type definitions for the new `event.locals` properties.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/app.d.ts
-import type { Session, SupabaseClient, User } from '@supabase/supabase-js'
-import type { Database } from './database.types.ts' // import generated 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 {}
- }
-}
-
-export {}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={5}>
-
-<StepHikeCompact.Details title="Create a Supabase client in your root layout">
-
-Create a Supabase client in your root `+layout.ts`. This client can be used to access Supabase from the client or the server. In order to get access to the Auth token on the server, use a `+layout.server.ts` file to pass in the session from `event.locals`.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/routes/+layout.ts
-import { createBrowserClient, createServerClient, isBrowser } from '@supabase/ssr'
-import { PUBLIC_SUPABASE_PUBLISHABLE_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'
-import type { LayoutLoad } from './$types'
-
-export const load: LayoutLoad = async ({ data, depends, fetch }) => {
- /**
- * Declare a dependency so the layout can be invalidated, for example, on
- * session refresh.
- */
- depends('supabase:auth')
-
- const supabase = isBrowser()
- ? createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
- global: {
- fetch,
- },
- })
- : createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
- global: {
- fetch,
- },
- cookies: {
- getAll() {
- return data.cookies
- },
- },
- })
-
- /**
- * 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()
-
- const {
- data: { user },
- } = await supabase.auth.getUser()
-
- return { session, supabase, user }
-}
-```
-
-```ts name=src/routes/+layout.server.ts
-import type { LayoutServerLoad } from './$types'
-
-export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
- const { session } = await safeGetSession()
- return {
- session,
- cookies: cookies.getAll(),
- }
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={6}>
-
-<StepHikeCompact.Details title="Listen to Auth events">
-
-Set up a listener for Auth events on the client, to handle session refreshes and signouts.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```svelte name=src/routes/+layout.svelte
-<script>
- import { invalidate } from '$app/navigation'
- import { onMount } from 'svelte'
-
- let { data, children } = $props()
- let { session, supabase } = $derived(data)
-
- onMount(() => {
- const { data } = supabase.auth.onAuthStateChange((_, newSession) => {
- if (newSession?.expires_at !== session?.expires_at) {
- invalidate('supabase:auth')
- }
- })
-
- return () => data.subscription.unsubscribe()
- })
-</script>
-
-{@render children()}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={7}>
-
-<StepHikeCompact.Details title="Create your first page">
-
-Create your first page. This example page calls Supabase from the server to get a list of colors from the database.
-
-This is an example of a public page that uses publicly readable data.
-
-To populate your database, run the [colors quickstart](/dashboard/project/_/sql/quickstarts) from your dashboard.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/routes/+page.server.ts
-import type { PageServerLoad } from './$types'
-
-export const load: PageServerLoad = async ({ locals: { supabase } }) => {
- const { data: colors } = await supabase.from('colors').select('name').limit(5).order('name')
- return { colors: colors ?? [] }
-}
-```
-
-```svelte name=src/routes/+page.svelte
-<script>
- let { data } = $props()
- let { colors } = $derived(data)
-</script>
-
-<h1>Welcome to Supabase!</h1>
-<ul>
- {#each colors as color}
- <li>{color.name}</li>
- {/each}
-</ul>
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={8}>
-
-<StepHikeCompact.Details title="Change the Auth confirmation path">
-
-If you have email confirmation turned on (the default), a new user will receive an email confirmation after signing up.
-
-Change the email template to support a server-side authentication flow.
-
-Go to the [Auth templates](/dashboard/project/_/auth/templates) page in your dashboard. In the `Confirm signup` template, change `{{ .ConfirmationURL }}` to `{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email`.
-
-</StepHikeCompact.Details>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={9}>
-
-<StepHikeCompact.Details title="Create a login page">
-
-Next, create a login page to let users sign up and log in.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/routes/auth/+page.server.ts
-import { redirect } from '@sveltejs/kit'
-
-import type { Actions } from './$types'
-
-export const actions: Actions = {
- signup: async ({ request, locals: { supabase } }) => {
- const formData = await request.formData()
- const email = formData.get('email') as string
- const password = formData.get('password') as string
-
- const { error } = await supabase.auth.signUp({ email, password })
- if (error) {
- console.error(error)
- redirect(303, '/auth/error')
- } else {
- redirect(303, '/')
- }
- },
- login: async ({ request, locals: { supabase } }) => {
- const formData = await request.formData()
- const email = formData.get('email') as string
- const password = formData.get('password') as string
-
- const { error } = await supabase.auth.signInWithPassword({ email, password })
- if (error) {
- console.error(error)
- redirect(303, '/auth/error')
- } else {
- redirect(303, '/private')
- }
- },
-}
-```
-
-```svelte name=src/routes/auth/+page.svelte
-<form method="POST" action="?/login">
- <label>
- Email
- <input name="email" type="email" />
- </label>
- <label>
- Password
- <input name="password" type="password" />
- </label>
- <button>Login</button>
- <button formaction="?/signup">Sign up</button>
-</form>
-```
-
-```svelte name=src/routes/auth/+layout.svelte
-<script>
- let { children } = $props()
-</script>
-
-<header>
- <nav>
- <a href="/">Home</a>
- </nav>
-</header>
-
-{@render children()}
-```
-
-```svelte name=src/routes/auth/error/+page.svelte
-<p>Login error</p>
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={10}>
-
-<StepHikeCompact.Details title="Create the signup confirmation route">
-
-Finish the signup flow by creating the API route to handle email verification.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/routes/auth/confirm/+server.ts
-import type { EmailOtpType } from '@supabase/supabase-js'
-import { redirect } from '@sveltejs/kit'
-
-import type { RequestHandler } from './$types'
-
-export const GET: RequestHandler = async ({ url, locals: { supabase } }) => {
- const token_hash = url.searchParams.get('token_hash')
- const type = url.searchParams.get('type') as EmailOtpType | null
- const next = url.searchParams.get('next') ?? '/'
-
- /**
- * Clean up the redirect URL by deleting the Auth flow parameters.
- *
- * `next` is preserved for now, because it's needed in the error case.
- */
- const redirectTo = new URL(url)
- redirectTo.pathname = next
- redirectTo.searchParams.delete('token_hash')
- redirectTo.searchParams.delete('type')
-
- if (token_hash && type) {
- const { error } = await supabase.auth.verifyOtp({ type, token_hash })
- if (!error) {
- redirectTo.searchParams.delete('next')
- redirect(303, redirectTo)
- }
- }
-
- redirectTo.pathname = '/auth/error'
- redirect(303, redirectTo)
-}
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-<StepHikeCompact.Step step={11}>
-
-<StepHikeCompact.Details title="Create private routes">
-
-Create private routes that can only be accessed by authenticated users. The routes in the `private` directory are protected by the route guard in `hooks.server.ts`.
-
-To ensure that `hooks.server.ts` runs for every nested path, put a `+layout.server.ts` file in the `private` directory. This file can be empty, but must exist to protect routes that don't have their own `+layout|page.server.ts`.
-
-</StepHikeCompact.Details>
-
-<StepHikeCompact.Code>
-
-<$CodeTabs>
-
-```ts name=src/routes/private/+layout.server.ts
-/**
- * This file is necessary to ensure protection of all routes in the `private`
- * directory. It makes the routes in this directory _dynamic_ routes, which
- * send a server request, and thus trigger `hooks.server.ts`.
- **/
-```
-
-```svelte name=src/routes/private/+layout.svelte
-<script>
- let { data, children } = $props()
- let { supabase } = $derived(data)
-
- const logout = async () => {
- const { error } = await supabase.auth.signOut()
- if (error) {
- console.error(error)
- }
- }
-</script>
-
-<header>
- <nav>
- <a href="/">Home</a>
- </nav>
- <button onclick={logout}>Logout</button>
-</header>
-<main>
- {@render children()}
-</main>
-```
-
-```sql name=SQL
--- Run this SQL against your database to create a `notes` table.
-
-create table notes (
- id bigint primary key generated always as identity,
- created_at timestamp with time zone not null default now(),
- user_id uuid references auth.users on delete cascade not null default auth.uid(),
- note text not null
-);
-
-alter table notes enable row level security;
-
-revoke all on table notes from authenticated;
-revoke all on table notes from anon;
-
-grant all (note) on table notes to authenticated;
-grant select (id) on table notes to authenticated;
-grant delete on table notes to authenticated;
-
-create policy "Users can access and modify their own notes"
-on notes
-for all
-to authenticated
-using ((select auth.uid()) = user_id);
-```
-
-```svelte name=src/routes/private/+page.server.ts
-import type { PageServerLoad } from './$types'
-
-export const load: PageServerLoad = async ({ depends, locals: { supabase } }) => {
- depends('supabase:db:notes')
- const { data: notes } = await supabase.from('notes').select('id,note').order('id')
- return { notes: notes ?? [] }
-}
-```
-
-```svelte name=src/routes/private/+page.svelte
-<script lang="ts">
- import { invalidate } from '$app/navigation'
- import type { EventHandler } from 'svelte/elements'
-
- import type { PageData } from './$types'
-
- let { data } = $props()
- let { notes, supabase, user } = $derived(data)
-
- const handleSubmit: EventHandler<SubmitEvent, HTMLFormElement> = async (evt) => {
- evt.preventDefault()
- if (!evt.target) return
-
- const form = evt.target as HTMLFormElement
-
- const note = (new FormData(form).get('note') ?? '') as string
- if (!note) return
-
- const { error } = await supabase.from('notes').insert({ note })
- if (error) console.error(error)
-
- invalidate('supabase:db:notes')
- form.reset()
- }
-</script>
-
-<h1>Private page for user: {user?.email}</h1>
-<h2>Notes</h2>
-<ul>
- {#each notes as note}
- <li>{note.note}</li>
- {/each}
-</ul>
-<form onsubmit={handleSubmit}>
- <label>
- Add a note
- <input name="note" type="text" />
- </label>
-</form>
-```
-
-</$CodeTabs>
-
-</StepHikeCompact.Code>
-
-</StepHikeCompact.Step>
-
-</StepHikeCompact>
diff --git a/apps/www/lib/redirects.js b/apps/www/lib/redirects.js
index 985b4b3ce98..174da21ded9 100644
--- a/apps/www/lib/redirects.js
+++ b/apps/www/lib/redirects.js
@@ -1298,6 +1298,18 @@ module.exports = [
source: '/docs/guides/auth/auth-helpers/auth-ui-overview',
destination: '/docs/guides/auth/auth-helpers/auth-ui',
},
+ {
+ permanent: false,
+ source: '/docs/guides/auth/server-side/nextjs',
+ destination:
+ '/docs/guides/auth/server-side/creating-a-client?queryGroups=framework&framework=nextjs',
+ },
+ {
+ permanent: false,
+ source: '/docs/guides/auth/server-side/sveltekit',
+ destination:
+ '/docs/guides/auth/server-side/creating-a-client?queryGroups=framework&framework=sveltekit',
+ },
{
permanent: true,
source: '/docs/guides/client-libraries',
diff --git a/examples/auth/hono-full/.env.example b/examples/auth/hono-full/.env.example
new file mode 100644
index 00000000000..671edd50acf
--- /dev/null
+++ b/examples/auth/hono-full/.env.example
@@ -0,0 +1,3 @@
+# Get your keys at https://supabase.com/dashboard/project/_/settings/api
+VITE_SUPABASE_URL=your_supabase_url
+VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
\ No newline at end of file
diff --git a/examples/auth/hono-full/.gitignore b/examples/auth/hono-full/.gitignore
new file mode 100644
index 00000000000..2eea525d885
--- /dev/null
+++ b/examples/auth/hono-full/.gitignore
@@ -0,0 +1 @@
+.env
\ No newline at end of file
diff --git a/examples/auth/hono/README.md b/examples/auth/hono-full/README.md
similarity index 100%
rename from examples/auth/hono/README.md
rename to examples/auth/hono-full/README.md
diff --git a/examples/auth/hono/package-lock.json b/examples/auth/hono-full/package-lock.json
similarity index 100%
rename from examples/auth/hono/package-lock.json
rename to examples/auth/hono-full/package-lock.json
diff --git a/examples/auth/hono-full/package.json b/examples/auth/hono-full/package.json
new file mode 100644
index 00000000000..395dcb74dad
--- /dev/null
+++ b/examples/auth/hono-full/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "hono-vite-jsx",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build --mode client && vite build"
+ },
+ "dependencies": {
+ "@hono/node-server": "^1.12.2",
+ "@supabase/ssr": "^0.5.2",
+ "@supabase/supabase-js": "^2.47.10",
+ "hono": "^4.9.7"
+ },
+ "devDependencies": {
+ "@hono/vite-build": "^1.1.0",
+ "@hono/vite-dev-server": "^0.17.0",
+ "@types/node": "^20.11.17",
+ "vite": "^5.4.2"
+ }
+}
diff --git a/examples/auth/hono/src/client.tsx b/examples/auth/hono-full/src/client.tsx
similarity index 100%
rename from examples/auth/hono/src/client.tsx
rename to examples/auth/hono-full/src/client.tsx
diff --git a/examples/auth/hono-full/src/index.tsx b/examples/auth/hono-full/src/index.tsx
new file mode 100644
index 00000000000..5acaf4801f8
--- /dev/null
+++ b/examples/auth/hono-full/src/index.tsx
@@ -0,0 +1,64 @@
+import { Hono } from 'hono';
+import { getSupabase, supabaseMiddleware } from './middleware/auth.middleware';
+
+const app = new Hono();
+app.use('*', supabaseMiddleware());
+
+const routes = app.get('/api/user', async (c) => {
+ const supabase = getSupabase(c);
+ const { data, error } = await supabase.auth.getUser();
+
+ if (error) console.log('error', error);
+
+ if (!data?.user) {
+ return c.json({
+ message: 'You are not logged in.',
+ });
+ }
+
+ return c.json({
+ message: 'You are logged in!',
+ userId: data.user,
+ });
+});
+
+app.get('/signout', async (c) => {
+ const supabase = getSupabase(c);
+ await supabase.auth.signOut();
+ console.log('Signed out server-side!');
+ return c.redirect('/');
+});
+
+app.get('/countries', async (c) => {
+ const supabase = getSupabase(c);
+ const { data, error } = await supabase.from('countries').select('*');
+ if (error) console.log(error);
+ return c.json(data);
+});
+
+export type AppType = typeof routes;
+
+app.get('/', (c) => {
+ return c.html(
+ <html lang="en">
+ <head>
+ <meta charSet="utf-8" />
+ <meta content="width=device-width, initial-scale=1" name="viewport" />
+ <link
+ rel="stylesheet"
+ href="https://cdn.simplecss.org/simple.min.css"
+ />
+ {import.meta.env.PROD ? (
+ <script type="module" src="/static/client.js" />
+ ) : (
+ <script type="module" src="/src/client.tsx" />
+ )}
+ </head>
+ <body>
+ <div id="root" />
+ </body>
+ </html>
+ );
+});
+
+export default app;
diff --git a/examples/auth/hono-full/src/middleware/auth.middleware.ts b/examples/auth/hono-full/src/middleware/auth.middleware.ts
new file mode 100644
index 00000000000..d9f34905000
--- /dev/null
+++ b/examples/auth/hono-full/src/middleware/auth.middleware.ts
@@ -0,0 +1,56 @@
+import { createServerClient, parseCookieHeader } from '@supabase/ssr';
+import { SupabaseClient } from '@supabase/supabase-js';
+import type { Context, MiddlewareHandler } from 'hono';
+import { env } from 'hono/adapter';
+import { setCookie } from 'hono/cookie';
+
+declare module 'hono' {
+ interface ContextVariableMap {
+ supabase: SupabaseClient;
+ }
+}
+
+export const getSupabase = (c: Context) => {
+ return c.get('supabase');
+};
+
+type SupabaseEnv = {
+ VITE_SUPABASE_URL: string;
+ VITE_SUPABASE_ANON_KEY: string;
+};
+
+export const supabaseMiddleware = (): MiddlewareHandler => {
+ return async (c, next) => {
+ const supabaseEnv = env<SupabaseEnv>(c);
+ const supabaseUrl =
+ supabaseEnv.VITE_SUPABASE_URL ?? import.meta.env.VITE_SUPABASE_URL;
+ const supabasePublishableKey =
+ supabaseEnv.VITE_SUPABASE_ANON_KEY ??
+ import.meta.env.VITE_SUPABASE_ANON_KEY;
+
+ if (!supabaseUrl) {
+ throw new Error('SUPABASE_URL missing!');
+ }
+
+ if (!supabasePublishableKey) {
+ throw new Error('SUPABASE_ANON_KEY missing!');
+ }
+
+ const supabase = createServerClient(supabaseUrl, supabasePublishableKey, {
+ cookies: {
+ getAll() {
+ return parseCookieHeader(c.req.header('Cookie') ?? '');
+ },
+ setAll(cookiesToSet) {
+ cookiesToSet.forEach(({ name, value, options }) =>
+ setCookie(c, name, value, options)
+ );
+ },
+ },
+ });
+
+ c.set('supabase', supabase);
+
+ await next();
+ };
+};
diff --git a/examples/auth/hono/supabase/.gitignore b/examples/auth/hono-full/supabase/.gitignore
similarity index 100%
rename from examples/auth/hono/supabase/.gitignore
rename to examples/auth/hono-full/supabase/.gitignore
diff --git a/examples/auth/hono/supabase/config.toml b/examples/auth/hono-full/supabase/config.toml
similarity index 100%
rename from examples/auth/hono/supabase/config.toml
rename to examples/auth/hono-full/supabase/config.toml
diff --git a/examples/auth/hono/supabase/seed.sql b/examples/auth/hono-full/supabase/seed.sql
similarity index 100%
rename from examples/auth/hono/supabase/seed.sql
rename to examples/auth/hono-full/supabase/seed.sql
diff --git a/examples/auth/hono/tsconfig.json b/examples/auth/hono-full/tsconfig.json
similarity index 100%
rename from examples/auth/hono/tsconfig.json
rename to examples/auth/hono-full/tsconfig.json
diff --git a/examples/auth/hono/vite.config.ts b/examples/auth/hono-full/vite.config.ts
similarity index 100%
rename from examples/auth/hono/vite.config.ts
rename to examples/auth/hono-full/vite.config.ts
diff --git a/examples/auth/hono/package.json b/examples/auth/hono/package.json
index 395dcb74dad..04b8f22d0bd 100644
--- a/examples/auth/hono/package.json
+++ b/examples/auth/hono/package.json
@@ -7,8 +7,8 @@
},
"dependencies": {
"@hono/node-server": "^1.12.2",
- "@supabase/ssr": "^0.5.2",
- "@supabase/supabase-js": "^2.47.10",
+ "@supabase/ssr": "latest",
+ "@supabase/supabase-js": "latest",
"hono": "^4.9.7"
},
"devDependencies": {
diff --git a/examples/auth/hono/src/index.tsx b/examples/auth/hono/src/index.tsx
index 5acaf4801f8..a80e376c8ce 100644
--- a/examples/auth/hono/src/index.tsx
+++ b/examples/auth/hono/src/index.tsx
@@ -1,64 +1,40 @@
-import { Hono } from 'hono';
-import { getSupabase, supabaseMiddleware } from './middleware/auth.middleware';
+import { Hono } from 'hono'
+import { getSupabase, supabaseMiddleware } from './middleware/auth.middleware'
-const app = new Hono();
-app.use('*', supabaseMiddleware());
+const app = new Hono()
+app.use('*', supabaseMiddleware())
-const routes = app.get('/api/user', async (c) => {
- const supabase = getSupabase(c);
- const { data, error } = await supabase.auth.getUser();
+app.get('/api/user', async (c) => {
+ const supabase = getSupabase(c)
+ const { data, error } = await supabase.auth.getClaims()
- if (error) console.log('error', error);
+ if (error) console.log('error', error)
if (!data?.user) {
return c.json({
message: 'You are not logged in.',
- });
+ })
}
return c.json({
message: 'You are logged in!',
userId: data.user,
- });
-});
+ })
+})
app.get('/signout', async (c) => {
- const supabase = getSupabase(c);
- await supabase.auth.signOut();
- console.log('Signed out server-side!');
- return c.redirect('/');
-});
+ const supabase = getSupabase(c)
+ await supabase.auth.signOut()
+ console.log('Signed out server-side!')
+ return c.redirect('/')
+})
+// Retrieve data with RLS enabled. The signed in user's auth token is automatically sent.
app.get('/countries', async (c) => {
- const supabase = getSupabase(c);
- const { data, error } = await supabase.from('countries').select('*');
- if (error) console.log(error);
- return c.json(data);
-});
+ const supabase = getSupabase(c)
+ const { data, error } = await supabase.from('countries').select('*')
+ if (error) console.log(error)
+ return c.json(data)
+})
-export type AppType = typeof routes;
-
-app.get('/', (c) => {
- return c.html(
- <html lang="en">
- <head>
- <meta charSet="utf-8" />
- <meta content="width=device-width, initial-scale=1" name="viewport" />
- <link
- rel="stylesheet"
- href="https://cdn.simplecss.org/simple.min.css"
- />
- {import.meta.env.PROD ? (
- <script type="module" src="/static/client.js" />
- ) : (
- <script type="module" src="/src/client.tsx" />
- )}
- </head>
- <body>
- <div id="root" />
- </body>
- </html>
- );
-});
-
-export default app;
+export default app
\ No newline at end of file
diff --git a/examples/auth/hono/src/middleware/auth.middleware.ts b/examples/auth/hono/src/middleware/auth.middleware.ts
index d9f34905000..7caeb4fbcb3 100644
--- a/examples/auth/hono/src/middleware/auth.middleware.ts
+++ b/examples/auth/hono/src/middleware/auth.middleware.ts
@@ -1,56 +1,51 @@
-import { createServerClient, parseCookieHeader } from '@supabase/ssr';
-import { SupabaseClient } from '@supabase/supabase-js';
-import type { Context, MiddlewareHandler } from 'hono';
-import { env } from 'hono/adapter';
-import { setCookie } from 'hono/cookie';
+import { createServerClient, parseCookieHeader } from '@supabase/ssr'
+import { SupabaseClient } from '@supabase/supabase-js'
+import type { Context, MiddlewareHandler } from 'hono'
+import { env } from 'hono/adapter'
+import { setCookie } from 'hono/cookie'
declare module 'hono' {
interface ContextVariableMap {
- supabase: SupabaseClient;
+ supabase: SupabaseClient
}
}
export const getSupabase = (c: Context) => {
- return c.get('supabase');
-};
+ return c.get('supabase')
+}
type SupabaseEnv = {
- VITE_SUPABASE_URL: string;
- VITE_SUPABASE_ANON_KEY: string;
-};
+ SUPABASE_URL: string
+ SUPABASE_PUBLISHABLE_KEY: string
+}
export const supabaseMiddleware = (): MiddlewareHandler => {
return async (c, next) => {
- const supabaseEnv = env<SupabaseEnv>(c);
- const supabaseUrl =
- supabaseEnv.VITE_SUPABASE_URL ?? import.meta.env.VITE_SUPABASE_URL;
- const supabasePublishableKey =
- supabaseEnv.VITE_SUPABASE_ANON_KEY ??
- import.meta.env.VITE_SUPABASE_ANON_KEY;
+ const supabaseEnv = env<SupabaseEnv>(c)
+ const supabaseUrl = supabaseEnv.SUPABASE_URL
+ const supabaseAnonKey = supabaseEnv.SUPABASE_PUBLISHABLE_KEY
if (!supabaseUrl) {
- throw new Error('SUPABASE_URL missing!');
+ throw new Error('SUPABASE_URL missing!')
}
- if (!supabasePublishableKey) {
- throw new Error('SUPABASE_ANON_KEY missing!');
+ if (!supabaseAnonKey) {
+ throw new Error('SUPABASE_PUBLISHABLE_KEY missing!')
}
- const supabase = createServerClient(supabaseUrl, supabasePublishableKey, {
+ const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
cookies: {
getAll() {
- return parseCookieHeader(c.req.header('Cookie') ?? '');
+ return parseCookieHeader(c.req.header('Cookie') ?? '')
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) =>
- setCookie(c, name, value, options)
- );
+ cookiesToSet.forEach(({ name, value, options }) => setCookie(c, name, value, options))
},
},
- });
+ })
- c.set('supabase', supabase);
+ c.set('supabase', supabase)
- await next();
- };
-};
+ await next()
+ }
+}
\ No newline at end of file
diff --git a/examples/auth/nextjs-full/.env.example b/examples/auth/nextjs-full/.env.example
new file mode 100644
index 00000000000..5f69cea9e2d
--- /dev/null
+++ b/examples/auth/nextjs-full/.env.example
@@ -0,0 +1,4 @@
+# Update these with your Supabase details from your project settings > API
+# https://app.supabase.com/project/_/settings/api
+NEXT_PUBLIC_SUPABASE_URL=your-project-url
+NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-key
diff --git a/examples/auth/nextjs-full/.gitignore b/examples/auth/nextjs-full/.gitignore
new file mode 100644
index 00000000000..fd3dbb571a1
--- /dev/null
+++ b/examples/auth/nextjs-full/.gitignore
@@ -0,0 +1,36 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+.yarn/install-state.gz
+
+# testing
+/coverage
+
+# next.js
+/.next/
+/out/
+
+# production
+/build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# local env files
+.env*.local
+
+# vercel
+.vercel
+
+# typescript
+*.tsbuildinfo
+next-env.d.ts
diff --git a/examples/auth/nextjs/README.md b/examples/auth/nextjs-full/README.md
similarity index 100%
rename from examples/auth/nextjs/README.md
rename to examples/auth/nextjs-full/README.md
diff --git a/examples/auth/nextjs/app/auth/callback/route.ts b/examples/auth/nextjs-full/app/auth/confirm/route.ts
similarity index 100%
rename from examples/auth/nextjs/app/auth/callback/route.ts
rename to examples/auth/nextjs-full/app/auth/confirm/route.ts
diff --git a/examples/auth/nextjs/app/error/page.tsx b/examples/auth/nextjs-full/app/error/page.tsx
similarity index 100%
rename from examples/auth/nextjs/app/error/page.tsx
rename to examples/auth/nextjs-full/app/error/page.tsx
diff --git a/examples/auth/nextjs/app/favicon.ico b/examples/auth/nextjs-full/app/favicon.ico
similarity index 100%
rename from examples/auth/nextjs/app/favicon.ico
rename to examples/auth/nextjs-full/app/favicon.ico
diff --git a/examples/auth/nextjs/app/globals.css b/examples/auth/nextjs-full/app/globals.css
similarity index 100%
rename from examples/auth/nextjs/app/globals.css
rename to examples/auth/nextjs-full/app/globals.css
diff --git a/examples/auth/nextjs/app/layout.tsx b/examples/auth/nextjs-full/app/layout.tsx
similarity index 100%
rename from examples/auth/nextjs/app/layout.tsx
rename to examples/auth/nextjs-full/app/layout.tsx
diff --git a/examples/auth/nextjs/app/login/actions.tsx b/examples/auth/nextjs-full/app/login/actions.ts
similarity index 100%
rename from examples/auth/nextjs/app/login/actions.tsx
rename to examples/auth/nextjs-full/app/login/actions.ts
diff --git a/examples/auth/nextjs/app/login/page.tsx b/examples/auth/nextjs-full/app/login/page.tsx
similarity index 100%
rename from examples/auth/nextjs/app/login/page.tsx
rename to examples/auth/nextjs-full/app/login/page.tsx
diff --git a/examples/auth/nextjs/app/login/submit-button.tsx b/examples/auth/nextjs-full/app/login/submit-button.tsx
similarity index 100%
rename from examples/auth/nextjs/app/login/submit-button.tsx
rename to examples/auth/nextjs-full/app/login/submit-button.tsx
diff --git a/examples/auth/nextjs/app/opengraph-image.png b/examples/auth/nextjs-full/app/opengraph-image.png
similarity index 100%
rename from examples/auth/nextjs/app/opengraph-image.png
rename to examples/auth/nextjs-full/app/opengraph-image.png
diff --git a/examples/auth/nextjs/app/page.tsx b/examples/auth/nextjs-full/app/page.tsx
similarity index 100%
rename from examples/auth/nextjs/app/page.tsx
rename to examples/auth/nextjs-full/app/page.tsx
diff --git a/examples/auth/nextjs/app/protected/page.tsx b/examples/auth/nextjs-full/app/private/page.tsx
similarity index 100%
rename from examples/auth/nextjs/app/protected/page.tsx
rename to examples/auth/nextjs-full/app/private/page.tsx
diff --git a/examples/auth/nextjs/app/twitter-image.png b/examples/auth/nextjs-full/app/twitter-image.png
similarity index 100%
rename from examples/auth/nextjs/app/twitter-image.png
rename to examples/auth/nextjs-full/app/twitter-image.png
diff --git a/examples/auth/nextjs/components/AuthButton.tsx b/examples/auth/nextjs-full/components/AuthButton.tsx
similarity index 100%
rename from examples/auth/nextjs/components/AuthButton.tsx
rename to examples/auth/nextjs-full/components/AuthButton.tsx
diff --git a/examples/auth/nextjs/components/DeployButton.tsx b/examples/auth/nextjs-full/components/DeployButton.tsx
similarity index 100%
rename from examples/auth/nextjs/components/DeployButton.tsx
rename to examples/auth/nextjs-full/components/DeployButton.tsx
diff --git a/examples/auth/nextjs/components/Header.tsx b/examples/auth/nextjs-full/components/Header.tsx
similarity index 100%
rename from examples/auth/nextjs/components/Header.tsx
rename to examples/auth/nextjs-full/components/Header.tsx
diff --git a/examples/auth/nextjs/components/NextLogo.tsx b/examples/auth/nextjs-full/components/NextLogo.tsx
similarity index 100%
rename from examples/auth/nextjs/components/NextLogo.tsx
rename to examples/auth/nextjs-full/components/NextLogo.tsx
diff --git a/examples/auth/nextjs/components/SupabaseLogo.tsx b/examples/auth/nextjs-full/components/SupabaseLogo.tsx
similarity index 100%
rename from examples/auth/nextjs/components/SupabaseLogo.tsx
rename to examples/auth/nextjs-full/components/SupabaseLogo.tsx
diff --git a/examples/auth/nextjs/components/tutorial/Code.tsx b/examples/auth/nextjs-full/components/tutorial/Code.tsx
similarity index 100%
rename from examples/auth/nextjs/components/tutorial/Code.tsx
rename to examples/auth/nextjs-full/components/tutorial/Code.tsx
diff --git a/examples/auth/nextjs/components/tutorial/ConnectSupabaseSteps.tsx b/examples/auth/nextjs-full/components/tutorial/ConnectSupabaseSteps.tsx
similarity index 100%
rename from examples/auth/nextjs/components/tutorial/ConnectSupabaseSteps.tsx
rename to examples/auth/nextjs-full/components/tutorial/ConnectSupabaseSteps.tsx
diff --git a/examples/auth/nextjs/components/tutorial/FetchDataSteps.tsx b/examples/auth/nextjs-full/components/tutorial/FetchDataSteps.tsx
similarity index 100%
rename from examples/auth/nextjs/components/tutorial/FetchDataSteps.tsx
rename to examples/auth/nextjs-full/components/tutorial/FetchDataSteps.tsx
diff --git a/examples/auth/nextjs/components/tutorial/SignUpUserSteps.tsx b/examples/auth/nextjs-full/components/tutorial/SignUpUserSteps.tsx
similarity index 100%
rename from examples/auth/nextjs/components/tutorial/SignUpUserSteps.tsx
rename to examples/auth/nextjs-full/components/tutorial/SignUpUserSteps.tsx
diff --git a/examples/auth/nextjs/components/tutorial/Step.tsx b/examples/auth/nextjs-full/components/tutorial/Step.tsx
similarity index 100%
rename from examples/auth/nextjs/components/tutorial/Step.tsx
rename to examples/auth/nextjs-full/components/tutorial/Step.tsx
diff --git a/examples/auth/nextjs-full/middleware.ts b/examples/auth/nextjs-full/middleware.ts
new file mode 100644
index 00000000000..8db86114c18
--- /dev/null
+++ b/examples/auth/nextjs-full/middleware.ts
@@ -0,0 +1,19 @@
+import { type NextRequest } from "next/server"
+import { updateSession } from "@/utils/supabase/middleware"
+
+export async function middleware(request: NextRequest) {
+ return await updateSession(request)
+}
+
+export const config = {
+ matcher: [
+ /*
+ * Match all request paths except for the ones starting with:
+ * - _next/static (static files)
+ * - _next/image (image optimization files)
+ * - favicon.ico (favicon file)
+ * Feel free to modify this pattern to include more paths.
+ */
+ "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
+ ],
+}
diff --git a/examples/auth/nextjs/next.config.js b/examples/auth/nextjs-full/next.config.js
similarity index 100%
rename from examples/auth/nextjs/next.config.js
rename to examples/auth/nextjs-full/next.config.js
diff --git a/examples/auth/nextjs/package-lock.json b/examples/auth/nextjs-full/package-lock.json
similarity index 100%
rename from examples/auth/nextjs/package-lock.json
rename to examples/auth/nextjs-full/package-lock.json
diff --git a/examples/auth/nextjs-full/package.json b/examples/auth/nextjs-full/package.json
new file mode 100644
index 00000000000..a9997ef9250
--- /dev/null
+++ b/examples/auth/nextjs-full/package.json
@@ -0,0 +1,26 @@
+{
+ "private": true,
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start"
+ },
+ "dependencies": {
+ "@supabase/ssr": "latest",
+ "@supabase/supabase-js": "latest",
+ "autoprefixer": "10.4.17",
+ "geist": "^1.2.1",
+ "next": "latest",
+ "postcss": "8.4.33",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "tailwindcss": "3.4.1",
+ "typescript": "5.3.3"
+ },
+ "devDependencies": {
+ "@types/node": "20.11.5",
+ "@types/react": "18.2.48",
+ "@types/react-dom": "18.2.18",
+ "encoding": "^0.1.13"
+ }
+}
diff --git a/examples/auth/nextjs/postcss.config.js b/examples/auth/nextjs-full/postcss.config.js
similarity index 100%
rename from examples/auth/nextjs/postcss.config.js
rename to examples/auth/nextjs-full/postcss.config.js
diff --git a/examples/auth/nextjs/supabase/.gitignore b/examples/auth/nextjs-full/supabase/.gitignore
similarity index 100%
rename from examples/auth/nextjs/supabase/.gitignore
rename to examples/auth/nextjs-full/supabase/.gitignore
diff --git a/examples/auth/nextjs/supabase/config.toml b/examples/auth/nextjs-full/supabase/config.toml
similarity index 100%
rename from examples/auth/nextjs/supabase/config.toml
rename to examples/auth/nextjs-full/supabase/config.toml
diff --git a/examples/auth/nextjs/supabase/seed.sql b/examples/auth/nextjs-full/supabase/seed.sql
similarity index 100%
rename from examples/auth/nextjs/supabase/seed.sql
rename to examples/auth/nextjs-full/supabase/seed.sql
diff --git a/examples/auth/nextjs/tailwind.config.js b/examples/auth/nextjs-full/tailwind.config.js
similarity index 100%
rename from examples/auth/nextjs/tailwind.config.js
rename to examples/auth/nextjs-full/tailwind.config.js
diff --git a/examples/auth/nextjs/tsconfig.json b/examples/auth/nextjs-full/tsconfig.json
similarity index 100%
rename from examples/auth/nextjs/tsconfig.json
rename to examples/auth/nextjs-full/tsconfig.json
diff --git a/examples/auth/nextjs-full/utils/supabase/client.ts b/examples/auth/nextjs-full/utils/supabase/client.ts
new file mode 100644
index 00000000000..cb5f10d6134
--- /dev/null
+++ b/examples/auth/nextjs-full/utils/supabase/client.ts
@@ -0,0 +1,8 @@
+import { createBrowserClient } from "@supabase/ssr"
+
+export function createClient() {
+ return createBrowserClient(
+ process.env.NEXT_PUBLIC_SUPABASE_URL!,
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
+ )
+}
diff --git a/examples/auth/nextjs-full/utils/supabase/middleware.ts b/examples/auth/nextjs-full/utils/supabase/middleware.ts
new file mode 100644
index 00000000000..ce48362634e
--- /dev/null
+++ b/examples/auth/nextjs-full/utils/supabase/middleware.ts
@@ -0,0 +1,63 @@
+import { createServerClient } from "@supabase/ssr"
+import { NextResponse, type NextRequest } from "next/server"
+
+export async function updateSession(request: NextRequest) {
+ let supabaseResponse = NextResponse.next({
+ request,
+ })
+
+ const supabase = createServerClient(
+ process.env.NEXT_PUBLIC_SUPABASE_URL!,
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
+ {
+ cookies: {
+ getAll() {
+ return request.cookies.getAll()
+ },
+ setAll(cookiesToSet) {
+ cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
+ supabaseResponse = NextResponse.next({
+ request,
+ })
+ cookiesToSet.forEach(({ name, value, options }) =>
+ supabaseResponse.cookies.set(name, value, options)
+ )
+ },
+ },
+ }
+ )
+
+ // IMPORTANT: Avoid writing any logic between createServerClient and
+ // supabase.auth.getUser(). A simple mistake could make it very hard to debug
+ // issues with users being randomly logged out.
+
+ const {
+ data: { user },
+ } = await supabase.auth.getUser()
+
+ if (
+ !user &&
+ !request.nextUrl.pathname.startsWith("/login") &&
+ !request.nextUrl.pathname.startsWith("/auth")
+ ) {
+ // no user, potentially respond by redirecting the user to the login page
+ const url = request.nextUrl.clone()
+ url.pathname = "/login"
+ return NextResponse.redirect(url)
+ }
+
+ // IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
+ // creating a new response object with NextResponse.next() make sure to:
+ // 1. Pass the request in it, like so:
+ // const myNewResponse = NextResponse.next({ request })
+ // 2. Copy over the cookies, like so:
+ // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
+ // 3. Change the myNewResponse object to fit your needs, but avoid changing
+ // the cookies!
+ // 4. Finally:
+ // return myNewResponse
+ // If this is not done, you may be causing the browser and server to go out
+ // of sync and terminate the user's session prematurely!
+
+ return supabaseResponse
+}
diff --git a/examples/auth/nextjs-full/utils/supabase/server.ts b/examples/auth/nextjs-full/utils/supabase/server.ts
new file mode 100644
index 00000000000..aed1ce1830e
--- /dev/null
+++ b/examples/auth/nextjs-full/utils/supabase/server.ts
@@ -0,0 +1,29 @@
+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() {
+ return cookieStore.getAll()
+ },
+ setAll(cookiesToSet) {
+ try {
+ cookiesToSet.forEach(({ name, value, options }) =>
+ cookieStore.set(name, value, options)
+ )
+ } catch {
+ // The `setAll` method was called from a Server Component.
+ // This can be ignored if you have middleware refreshing
+ // user sessions.
+ }
+ },
+ },
+ }
+ )
+}
diff --git a/examples/auth/nextjs/utils/supabase/client.ts b/examples/auth/nextjs/utils/supabase/client.ts
index cb5f10d6134..1d920caab33 100644
--- a/examples/auth/nextjs/utils/supabase/client.ts
+++ b/examples/auth/nextjs/utils/supabase/client.ts
@@ -1,8 +1,8 @@
-import { createBrowserClient } from "@supabase/ssr"
+import { createBrowserClient } from '@supabase/ssr'
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
)
-}
+}
\ No newline at end of file
diff --git a/examples/auth/nextjs/utils/supabase/middleware.ts b/examples/auth/nextjs/utils/supabase/middleware.ts
index ce48362634e..38ee89646fb 100644
--- a/examples/auth/nextjs/utils/supabase/middleware.ts
+++ b/examples/auth/nextjs/utils/supabase/middleware.ts
@@ -1,5 +1,5 @@
-import { createServerClient } from "@supabase/ssr"
-import { NextResponse, type NextRequest } from "next/server"
+import { createServerClient } from '@supabase/ssr'
+import { NextResponse, type NextRequest } from 'next/server'
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
@@ -15,34 +15,33 @@ export async function updateSession(request: NextRequest) {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
+ cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({
request,
})
- cookiesToSet.forEach(({ name, value, options }) =>
- supabaseResponse.cookies.set(name, value, options)
- )
+ cookiesToSet.forEach(({ name, value }) => supabaseResponse.cookies.set(name, value))
},
},
}
)
// IMPORTANT: Avoid writing any logic between createServerClient and
- // supabase.auth.getUser(). A simple mistake could make it very hard to debug
+ // supabase.auth.getClaims(). A simple mistake could make it very hard to debug
// issues with users being randomly logged out.
- const {
- data: { user },
- } = await supabase.auth.getUser()
+ // IMPORTANT: Don't remove getClaims()
+ const { data } = await supabase.auth.getClaims()
+
+ const user = data?.claims
if (
!user &&
- !request.nextUrl.pathname.startsWith("/login") &&
- !request.nextUrl.pathname.startsWith("/auth")
+ !request.nextUrl.pathname.startsWith('/login') &&
+ !request.nextUrl.pathname.startsWith('/auth')
) {
// no user, potentially respond by redirecting the user to the login page
const url = request.nextUrl.clone()
- url.pathname = "/login"
+ url.pathname = '/login'
return NextResponse.redirect(url)
}
diff --git a/examples/auth/nextjs/utils/supabase/server.ts b/examples/auth/nextjs/utils/supabase/server.ts
index aed1ce1830e..cd04cee93ed 100644
--- a/examples/auth/nextjs/utils/supabase/server.ts
+++ b/examples/auth/nextjs/utils/supabase/server.ts
@@ -14,9 +14,7 @@ export async function createClient() {
},
setAll(cookiesToSet) {
try {
- cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options)
- )
+ cookiesToSet.forEach(({ name, value }) => cookieStore.set(name, value))
} catch {
// The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
diff --git a/examples/auth/sveltekit-full/package-lock.json b/examples/auth/sveltekit-full/package-lock.json
new file mode 100644
index 00000000000..a384ad5f655
--- /dev/null
+++ b/examples/auth/sveltekit-full/package-lock.json
@@ -0,0 +1,185 @@
+{
+ "name": "sveltekit",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "sveltekit",
+ "version": "1.0.0",
+ "license": "ISC",
+ "dependencies": {
+ "@supabase/ssr": "^0.6.1",
+ "@supabase/supabase-js": "^2.55.0"
+ }
+ },
+ "node_modules/@supabase/auth-js": {
+ "version": "2.71.1",
+ "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.71.1.tgz",
+ "integrity": "sha512-mMIQHBRc+SKpZFRB2qtupuzulaUhFYupNyxqDj5Jp/LyPvcWvjaJzZzObv6URtL/O6lPxkanASnotGtNpS3H2Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/functions-js": {
+ "version": "2.4.5",
+ "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.4.5.tgz",
+ "integrity": "sha512-v5GSqb9zbosquTo6gBwIiq7W9eQ7rE5QazsK/ezNiQXdCbY+bH8D9qEaBIkhVvX4ZRW5rP03gEfw5yw9tiq4EQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/node-fetch": {
+ "version": "2.6.15",
+ "resolved": "https://registry.npmjs.org/@supabase/node-fetch/-/node-fetch-2.6.15.tgz",
+ "integrity": "sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==",
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-url": "^5.0.0"
+ },
+ "engines": {
+ "node": "4.x || >=6.0.0"
+ }
+ },
+ "node_modules/@supabase/postgrest-js": {
+ "version": "1.19.4",
+ "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-1.19.4.tgz",
+ "integrity": "sha512-O4soKqKtZIW3olqmbXXbKugUtByD2jPa8kL2m2c1oozAO11uCcGrRhkZL0kVxjBLrXHE0mdSkFsMj7jDSfyNpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/realtime-js": {
+ "version": "2.15.1",
+ "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.15.1.tgz",
+ "integrity": "sha512-edRFa2IrQw50kNntvUyS38hsL7t2d/psah6om6aNTLLcWem0R6bOUq7sk7DsGeSlNfuwEwWn57FdYSva6VddYw==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.13",
+ "@types/phoenix": "^1.6.6",
+ "@types/ws": "^8.18.1",
+ "ws": "^8.18.2"
+ }
+ },
+ "node_modules/@supabase/ssr": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/@supabase/ssr/-/ssr-0.6.1.tgz",
+ "integrity": "sha512-QtQgEMvaDzr77Mk3vZ3jWg2/y+D8tExYF7vcJT+wQ8ysuvOeGGjYbZlvj5bHYsj/SpC0bihcisnwPrM4Gp5G4g==",
+ "license": "MIT",
+ "dependencies": {
+ "cookie": "^1.0.1"
+ },
+ "peerDependencies": {
+ "@supabase/supabase-js": "^2.43.4"
+ }
+ },
+ "node_modules/@supabase/storage-js": {
+ "version": "2.11.0",
+ "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.11.0.tgz",
+ "integrity": "sha512-Y+kx/wDgd4oasAgoAq0bsbQojwQ+ejIif8uczZ9qufRHWFLMU5cODT+ApHsSrDufqUcVKt+eyxtOXSkeh2v9ww==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/supabase-js": {
+ "version": "2.55.0",
+ "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.55.0.tgz",
+ "integrity": "sha512-Y1uV4nEMjQV1x83DGn7+Z9LOisVVRlY1geSARrUHbXWgbyKLZ6/08dvc0Us1r6AJ4tcKpwpCZWG9yDQYo1JgHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/auth-js": "2.71.1",
+ "@supabase/functions-js": "2.4.5",
+ "@supabase/node-fetch": "2.6.15",
+ "@supabase/postgrest-js": "1.19.4",
+ "@supabase/realtime-js": "2.15.1",
+ "@supabase/storage-js": "^2.10.4"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "24.3.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz",
+ "integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.10.0"
+ }
+ },
+ "node_modules/@types/phoenix": {
+ "version": "1.6.6",
+ "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.6.tgz",
+ "integrity": "sha512-PIzZZlEppgrpoT2QgbnDU+MMzuR6BbCjllj0bM70lWoejMeNJAxCchxnv7J3XFkI8MpygtRpzXrIlmWUBclP5A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
+ "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
+ "license": "MIT"
+ },
+ "node_modules/undici-types": {
+ "version": "7.10.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz",
+ "integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==",
+ "license": "MIT"
+ },
+ "node_modules/webidl-conversions": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/whatwg-url": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+ "license": "MIT",
+ "dependencies": {
+ "tr46": "~0.0.3",
+ "webidl-conversions": "^3.0.0"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/examples/auth/sveltekit-full/package.json b/examples/auth/sveltekit-full/package.json
new file mode 100644
index 00000000000..e05e0a7328f
--- /dev/null
+++ b/examples/auth/sveltekit-full/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "sveltekit",
+ "version": "1.0.0",
+ "description": "",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "@supabase/ssr": "^0.6.1",
+ "@supabase/supabase-js": "^2.55.0"
+ }
+}
diff --git a/examples/auth/sveltekit-full/src/app.d.ts b/examples/auth/sveltekit-full/src/app.d.ts
new file mode 100644
index 00000000000..9a0cf33671d
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/app.d.ts
@@ -0,0 +1,21 @@
+import type { Session, SupabaseClient, User } from '@supabase/supabase-js'
+import type { Database } from './database.types.ts' // import generated 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 {}
+ }
+}
+
+export {}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/hooks.server.ts b/examples/auth/sveltekit-full/src/hooks.server.ts
new file mode 100644
index 00000000000..b46b7434525
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/hooks.server.ts
@@ -0,0 +1,81 @@
+import { createServerClient } from '@supabase/ssr'
+import { type Handle, redirect } from '@sveltejs/kit'
+import { sequence } from '@sveltejs/kit/hooks'
+
+import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY } from '$env/static/public'
+
+const supabase: Handle = async ({ event, resolve }) => {
+ /**
+ * Creates a Supabase client specific to this server request.
+ *
+ * The Supabase client gets the Auth token from the request cookies.
+ */
+ event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
+ cookies: {
+ getAll: () => event.cookies.getAll(),
+ /**
+ * SvelteKit's cookies API requires `path` to be explicitly set in
+ * the cookie options. Setting `path` to `/` replicates previous/
+ * standard behavior.
+ */
+ setAll: (cookiesToSet) => {
+ cookiesToSet.forEach(({ name, value, options }) => {
+ event.cookies.set(name, value, { ...options, path: '/' })
+ })
+ },
+ },
+ })
+
+ /**
+ * 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) {
+ /**
+ * Supabase libraries use the `content-range` and `x-supabase-api-version`
+ * headers, so we need to tell SvelteKit to pass it through.
+ */
+ return name === 'content-range' || name === 'x-supabase-api-version'
+ },
+ })
+}
+
+const authGuard: Handle = async ({ event, resolve }) => {
+ const { session, user } = await event.locals.safeGetSession()
+ event.locals.session = session
+ event.locals.user = user
+
+ if (!event.locals.session && event.url.pathname.startsWith('/private')) {
+ redirect(303, '/auth')
+ }
+
+ if (event.locals.session && event.url.pathname === '/auth') {
+ redirect(303, '/private')
+ }
+
+ return resolve(event)
+}
+
+export const handle: Handle = sequence(supabase, authGuard)
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/+layout.server.ts b/examples/auth/sveltekit-full/src/routes/+layout.server.ts
new file mode 100644
index 00000000000..9f34b086b04
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/+layout.server.ts
@@ -0,0 +1,10 @@
+import type { LayoutServerLoad } from './$types'
+
+export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
+ const { session, user } = await safeGetSession()
+ return {
+ session,
+ user,
+ cookies: cookies.getAll(),
+ }
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/+layout.svelte b/examples/auth/sveltekit-full/src/routes/+layout.svelte
new file mode 100644
index 00000000000..f2ee8acd1f6
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/+layout.svelte
@@ -0,0 +1,19 @@
+<script>
+ import { invalidate } from '$app/navigation'
+ import { onMount } from 'svelte'
+
+ let { data, children } = $props()
+ let { session, supabase } = $derived(data)
+
+ onMount(() => {
+ const { data } = supabase.auth.onAuthStateChange((_, newSession) => {
+ if (newSession?.expires_at !== session?.expires_at) {
+ invalidate('supabase:auth')
+ }
+ })
+
+ return () => data.subscription.unsubscribe()
+ })
+</script>
+
+{@render children()}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/+layout.ts b/examples/auth/sveltekit-full/src/routes/+layout.ts
new file mode 100644
index 00000000000..371ba776b02
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/+layout.ts
@@ -0,0 +1,43 @@
+import { createBrowserClient, createServerClient, isBrowser } from '@supabase/ssr'
+import { PUBLIC_SUPABASE_PUBLISHABLE_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'
+import type { LayoutLoad } from './$types'
+
+export const load: LayoutLoad = async ({ data, depends, fetch }) => {
+ /**
+ * Declare a dependency so the layout can be invalidated, for example, on
+ * session refresh.
+ */
+ depends('supabase:auth')
+
+ const supabase = isBrowser()
+ ? createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
+ global: {
+ fetch,
+ },
+ })
+ : createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
+ global: {
+ fetch,
+ },
+ cookies: {
+ getAll() {
+ return data.cookies
+ },
+ },
+ })
+
+ /**
+ * 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()
+
+ const {
+ data: { user },
+ } = await supabase.auth.getUser()
+
+ return { session, supabase, user }
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/+page.server.ts b/examples/auth/sveltekit-full/src/routes/+page.server.ts
new file mode 100644
index 00000000000..f3d568acb27
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/+page.server.ts
@@ -0,0 +1,6 @@
+import type { PageServerLoad } from './$types'
+
+export const load: PageServerLoad = async ({ locals: { supabase } }) => {
+ const { data: colors } = await supabase.from('colors').select('name').limit(5).order('name')
+ return { colors: colors ?? [] }
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/+page.svelte b/examples/auth/sveltekit-full/src/routes/+page.svelte
new file mode 100644
index 00000000000..82317928449
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/+page.svelte
@@ -0,0 +1,11 @@
+<script>
+ let { data } = $props()
+ let { colors } = $derived(data)
+</script>
+
+<h1>Welcome to Supabase!</h1>
+<ul>
+ {#each colors as color}
+ <li>{color.name}</li>
+ {/each}
+</ul>
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/auth/+layout.svelte b/examples/auth/sveltekit-full/src/routes/auth/+layout.svelte
new file mode 100644
index 00000000000..042ea05cce7
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/auth/+layout.svelte
@@ -0,0 +1,11 @@
+<script>
+ let { children } = $props()
+</script>
+
+<header>
+ <nav>
+ <a href="/">Home</a>
+ </nav>
+</header>
+
+{@render children()}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/auth/+page.server.ts b/examples/auth/sveltekit-full/src/routes/auth/+page.server.ts
new file mode 100644
index 00000000000..ea166853c6b
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/auth/+page.server.ts
@@ -0,0 +1,32 @@
+import { redirect } from '@sveltejs/kit'
+
+import type { Actions } from './$types'
+
+export const actions: Actions = {
+ signup: async ({ request, locals: { supabase } }) => {
+ const formData = await request.formData()
+ const email = formData.get('email') as string
+ const password = formData.get('password') as string
+
+ const { error } = await supabase.auth.signUp({ email, password })
+ if (error) {
+ console.error(error)
+ redirect(303, '/auth/error')
+ } else {
+ redirect(303, '/')
+ }
+ },
+ login: async ({ request, locals: { supabase } }) => {
+ const formData = await request.formData()
+ const email = formData.get('email') as string
+ const password = formData.get('password') as string
+
+ const { error } = await supabase.auth.signInWithPassword({ email, password })
+ if (error) {
+ console.error(error)
+ redirect(303, '/auth/error')
+ } else {
+ redirect(303, '/private')
+ }
+ },
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/auth/+page.svelte b/examples/auth/sveltekit-full/src/routes/auth/+page.svelte
new file mode 100644
index 00000000000..cded2fe8964
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/auth/+page.svelte
@@ -0,0 +1,12 @@
+<form method="POST" action="?/login">
+ <label>
+ Email
+ <input name="email" type="email" />
+ </label>
+ <label>
+ Password
+ <input name="password" type="password" />
+ </label>
+ <button>Login</button>
+ <button formaction="?/signup">Sign up</button>
+</form>
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/auth/confirm/+server.ts b/examples/auth/sveltekit-full/src/routes/auth/confirm/+server.ts
new file mode 100644
index 00000000000..4fd0574fc11
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/auth/confirm/+server.ts
@@ -0,0 +1,31 @@
+import type { EmailOtpType } from '@supabase/supabase-js'
+import { redirect } from '@sveltejs/kit'
+
+import type { RequestHandler } from './$types'
+
+export const GET: RequestHandler = async ({ url, locals: { supabase } }) => {
+ const token_hash = url.searchParams.get('token_hash')
+ const type = url.searchParams.get('type') as EmailOtpType | null
+ const next = url.searchParams.get('next') ?? '/'
+
+ /**
+ * Clean up the redirect URL by deleting the Auth flow parameters.
+ *
+ * `next` is preserved for now, because it's needed in the error case.
+ */
+ const redirectTo = new URL(url)
+ redirectTo.pathname = next
+ redirectTo.searchParams.delete('token_hash')
+ redirectTo.searchParams.delete('type')
+
+ if (token_hash && type) {
+ const { error } = await supabase.auth.verifyOtp({ type, token_hash })
+ if (!error) {
+ redirectTo.searchParams.delete('next')
+ redirect(303, redirectTo)
+ }
+ }
+
+ redirectTo.pathname = '/auth/error'
+ redirect(303, redirectTo)
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/auth/error/+page.svelte b/examples/auth/sveltekit-full/src/routes/auth/error/+page.svelte
new file mode 100644
index 00000000000..0176f4c72e6
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/auth/error/+page.svelte
@@ -0,0 +1 @@
+<p>Login error</p>
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/private/+layout.server.ts b/examples/auth/sveltekit-full/src/routes/private/+layout.server.ts
new file mode 100644
index 00000000000..803cddb8d16
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/private/+layout.server.ts
@@ -0,0 +1,5 @@
+/**
+ * This file is necessary to ensure protection of all routes in the `private`
+ * directory. It makes the routes in this directory _dynamic_ routes, which
+ * send a server request, and thus trigger `hooks.server.ts`.
+ **/
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/private/+layout.svelte b/examples/auth/sveltekit-full/src/routes/private/+layout.svelte
new file mode 100644
index 00000000000..c58284f3471
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/private/+layout.svelte
@@ -0,0 +1,21 @@
+<script>
+ let { data, children } = $props()
+ let { supabase } = $derived(data)
+
+ const logout = async () => {
+ const { error } = await supabase.auth.signOut()
+ if (error) {
+ console.error(error)
+ }
+ }
+</script>
+
+<header>
+ <nav>
+ <a href="/">Home</a>
+ </nav>
+ <button onclick={logout}>Logout</button>
+</header>
+<main>
+ {@render children()}
+</main>
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/private/+page.server.ts b/examples/auth/sveltekit-full/src/routes/private/+page.server.ts
new file mode 100644
index 00000000000..00dc6b7c9c3
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/private/+page.server.ts
@@ -0,0 +1,7 @@
+import type { PageServerLoad } from './$types'
+
+export const load: PageServerLoad = async ({ depends, locals: { supabase } }) => {
+ depends('supabase:db:notes')
+ const { data: notes } = await supabase.from('notes').select('id,note').order('id')
+ return { notes: notes ?? [] }
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit-full/src/routes/private/+page.svelte b/examples/auth/sveltekit-full/src/routes/private/+page.svelte
new file mode 100644
index 00000000000..e924b9e8285
--- /dev/null
+++ b/examples/auth/sveltekit-full/src/routes/private/+page.svelte
@@ -0,0 +1,39 @@
+<script lang="ts">
+ import { invalidate } from '$app/navigation'
+ import type { EventHandler } from 'svelte/elements'
+
+ import type { PageData } from './$types'
+
+ let { data } = $props()
+ let { notes, supabase, user } = $derived(data)
+
+ const handleSubmit: EventHandler<SubmitEvent, HTMLFormElement> = async (evt) => {
+ evt.preventDefault()
+ if (!evt.target) return
+
+ const form = evt.target as HTMLFormElement
+
+ const note = (new FormData(form).get('note') ?? '') as string
+ if (!note) return
+
+ const { error } = await supabase.from('notes').insert({ note })
+ if (error) console.error(error)
+
+ invalidate('supabase:db:notes')
+ form.reset()
+ }
+</script>
+
+<h1>Private page for user: {user?.email}</h1>
+<h2>Notes</h2>
+<ul>
+ {#each notes as note}
+ <li>{note.note}</li>
+ {/each}
+</ul>
+<form onsubmit={handleSubmit}>
+ <label>
+ Add a note
+ <input name="note" type="text" />
+ </label>
+</form>
\ No newline at end of file
diff --git a/examples/auth/sveltekit/package-lock.json b/examples/auth/sveltekit/package-lock.json
new file mode 100644
index 00000000000..a384ad5f655
--- /dev/null
+++ b/examples/auth/sveltekit/package-lock.json
@@ -0,0 +1,185 @@
+{
+ "name": "sveltekit",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "sveltekit",
+ "version": "1.0.0",
+ "license": "ISC",
+ "dependencies": {
+ "@supabase/ssr": "^0.6.1",
+ "@supabase/supabase-js": "^2.55.0"
+ }
+ },
+ "node_modules/@supabase/auth-js": {
+ "version": "2.71.1",
+ "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.71.1.tgz",
+ "integrity": "sha512-mMIQHBRc+SKpZFRB2qtupuzulaUhFYupNyxqDj5Jp/LyPvcWvjaJzZzObv6URtL/O6lPxkanASnotGtNpS3H2Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/functions-js": {
+ "version": "2.4.5",
+ "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.4.5.tgz",
+ "integrity": "sha512-v5GSqb9zbosquTo6gBwIiq7W9eQ7rE5QazsK/ezNiQXdCbY+bH8D9qEaBIkhVvX4ZRW5rP03gEfw5yw9tiq4EQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/node-fetch": {
+ "version": "2.6.15",
+ "resolved": "https://registry.npmjs.org/@supabase/node-fetch/-/node-fetch-2.6.15.tgz",
+ "integrity": "sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==",
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-url": "^5.0.0"
+ },
+ "engines": {
+ "node": "4.x || >=6.0.0"
+ }
+ },
+ "node_modules/@supabase/postgrest-js": {
+ "version": "1.19.4",
+ "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-1.19.4.tgz",
+ "integrity": "sha512-O4soKqKtZIW3olqmbXXbKugUtByD2jPa8kL2m2c1oozAO11uCcGrRhkZL0kVxjBLrXHE0mdSkFsMj7jDSfyNpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/realtime-js": {
+ "version": "2.15.1",
+ "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.15.1.tgz",
+ "integrity": "sha512-edRFa2IrQw50kNntvUyS38hsL7t2d/psah6om6aNTLLcWem0R6bOUq7sk7DsGeSlNfuwEwWn57FdYSva6VddYw==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.13",
+ "@types/phoenix": "^1.6.6",
+ "@types/ws": "^8.18.1",
+ "ws": "^8.18.2"
+ }
+ },
+ "node_modules/@supabase/ssr": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/@supabase/ssr/-/ssr-0.6.1.tgz",
+ "integrity": "sha512-QtQgEMvaDzr77Mk3vZ3jWg2/y+D8tExYF7vcJT+wQ8ysuvOeGGjYbZlvj5bHYsj/SpC0bihcisnwPrM4Gp5G4g==",
+ "license": "MIT",
+ "dependencies": {
+ "cookie": "^1.0.1"
+ },
+ "peerDependencies": {
+ "@supabase/supabase-js": "^2.43.4"
+ }
+ },
+ "node_modules/@supabase/storage-js": {
+ "version": "2.11.0",
+ "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.11.0.tgz",
+ "integrity": "sha512-Y+kx/wDgd4oasAgoAq0bsbQojwQ+ejIif8uczZ9qufRHWFLMU5cODT+ApHsSrDufqUcVKt+eyxtOXSkeh2v9ww==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
+ "node_modules/@supabase/supabase-js": {
+ "version": "2.55.0",
+ "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.55.0.tgz",
+ "integrity": "sha512-Y1uV4nEMjQV1x83DGn7+Z9LOisVVRlY1geSARrUHbXWgbyKLZ6/08dvc0Us1r6AJ4tcKpwpCZWG9yDQYo1JgHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/auth-js": "2.71.1",
+ "@supabase/functions-js": "2.4.5",
+ "@supabase/node-fetch": "2.6.15",
+ "@supabase/postgrest-js": "1.19.4",
+ "@supabase/realtime-js": "2.15.1",
+ "@supabase/storage-js": "^2.10.4"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "24.3.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz",
+ "integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.10.0"
+ }
+ },
+ "node_modules/@types/phoenix": {
+ "version": "1.6.6",
+ "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.6.tgz",
+ "integrity": "sha512-PIzZZlEppgrpoT2QgbnDU+MMzuR6BbCjllj0bM70lWoejMeNJAxCchxnv7J3XFkI8MpygtRpzXrIlmWUBclP5A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
+ "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
+ "license": "MIT"
+ },
+ "node_modules/undici-types": {
+ "version": "7.10.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz",
+ "integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==",
+ "license": "MIT"
+ },
+ "node_modules/webidl-conversions": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/whatwg-url": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+ "license": "MIT",
+ "dependencies": {
+ "tr46": "~0.0.3",
+ "webidl-conversions": "^3.0.0"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/examples/auth/sveltekit/package.json b/examples/auth/sveltekit/package.json
new file mode 100644
index 00000000000..e05e0a7328f
--- /dev/null
+++ b/examples/auth/sveltekit/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "sveltekit",
+ "version": "1.0.0",
+ "description": "",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "@supabase/ssr": "^0.6.1",
+ "@supabase/supabase-js": "^2.55.0"
+ }
+}
diff --git a/examples/auth/sveltekit/src/app.d.ts b/examples/auth/sveltekit/src/app.d.ts
new file mode 100644
index 00000000000..9a0cf33671d
--- /dev/null
+++ b/examples/auth/sveltekit/src/app.d.ts
@@ -0,0 +1,21 @@
+import type { Session, SupabaseClient, User } from '@supabase/supabase-js'
+import type { Database } from './database.types.ts' // import generated 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 {}
+ }
+}
+
+export {}
\ No newline at end of file
diff --git a/examples/auth/sveltekit/src/hooks.server.ts b/examples/auth/sveltekit/src/hooks.server.ts
new file mode 100644
index 00000000000..54ce5f3dc52
--- /dev/null
+++ b/examples/auth/sveltekit/src/hooks.server.ts
@@ -0,0 +1,55 @@
+import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY } from '$env/static/public'
+import { createServerClient } from '@supabase/ssr'
+import type { Handle } from '@sveltejs/kit'
+
+export const handle: Handle = async ({ event, resolve }) => {
+ event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
+ cookies: {
+ getAll() {
+ return event.cookies.getAll()
+ },
+ setAll(cookiesToSet) {
+ /**
+ * 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
+ * will replicate previous/standard behavior (https://kit.svelte.dev/docs/types#public-types-cookies)
+ */
+ cookiesToSet.forEach(({ name, value, options }) =>
+ event.cookies.set(name, value, { ...options, path: '/' })
+ )
+ },
+ },
+ })
+
+ /**
+ * 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'
+ },
+ })
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit/src/routes/+layout.server.ts b/examples/auth/sveltekit/src/routes/+layout.server.ts
new file mode 100644
index 00000000000..b86a13eee15
--- /dev/null
+++ b/examples/auth/sveltekit/src/routes/+layout.server.ts
@@ -0,0 +1,11 @@
+import type { LayoutServerLoad } from './$types'
+
+export const load: LayoutServerLoad = async ({ locals: { safeGetSession }, cookies }) => {
+ const { session, user } = await safeGetSession()
+
+ return {
+ session,
+ user,
+ cookies: cookies.getAll(),
+ }
+}
\ No newline at end of file
diff --git a/examples/auth/sveltekit/src/routes/+layout.ts b/examples/auth/sveltekit/src/routes/+layout.ts
new file mode 100644
index 00000000000..2868b58dd09
--- /dev/null
+++ b/examples/auth/sveltekit/src/routes/+layout.ts
@@ -0,0 +1,35 @@
+import { PUBLIC_SUPABASE_PUBLISHABLE_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'
+import type { LayoutLoad } from './$types'
+import { createBrowserClient, createServerClient, isBrowser } from '@supabase/ssr'
+
+export const load: LayoutLoad = async ({ fetch, data, depends }) => {
+ depends('supabase:auth')
+
+ const supabase = isBrowser()
+ ? createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
+ global: {
+ fetch,
+ },
+ })
+ : createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_PUBLISHABLE_KEY, {
+ global: {
+ fetch,
+ },
+ cookies: {
+ getAll() {
+ return data.cookies
+ },
+ },
+ })
+
+ /**
+ * 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()
+
+ return { supabase, session }
+}
\ No newline at end of file