本页还没有译文
本页 171 段还没译成日本語,下面显示的是英文原文。Creating a Supabase client for SSR
还没翻译译自英文(supabase.com)本页 171 段都还没译
Learn how to configure your Supabase client to use cookies. Your app can then render on the server with the user already signed in.
Server-Side Rendering (SSR) with Supabase requires cookie-based session storage. The @supabase/ssr package handles this for JavaScript and TypeScript applications.
Use this guide to:
- Install the packages.
- Set environment variables.
- Create a client for your framework.
Refer to these reference sections to make better decisions about verifying users and caching responses:
- Choosing an auth method, before you write code that checks who the user is.
- Caching considerations, if you deploy behind a CDN or use ISR.
Install
Install the @supabase/supabase-js and @supabase/ssr helper packages:
npm install @supabase/supabase-js @supabase/ssryarn add @supabase/supabase-js @supabase/ssrpnpm add @supabase/supabase-js @supabase/ssrSet environment variables
Create a .env.local file in the project root directory. In the file, set the project's Supabase URL and Key:
Get API details
To interact with data in database tables, you use the client libraries that wrap the auto-generated Data API endpoints, authenticating using the Project URL and key from the project Connect dialog.
Project URL: https://<project-ref>.supabase.co (find yours in the dashboard)
Publishable key: sb_publishable_... (find yours in the dashboard)
Note
See API keys for a full explanation of all key types, their uses, and where to find them.
NEXT_PUBLIC_SUPABASE_URL=supabase_project_url
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyPUBLIC_SUPABASE_URL=supabase_project_url
PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyPUBLIC_SUPABASE_URL=supabase_project_url
PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keySUPABASE_URL=supabase_project_url
SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyNUXT_PUBLIC_SUPABASE_URL=supabase_project_url
NUXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyIn nuxt.config.ts, map these public env vars into runtime config keys used by the examples below:
export default defineNuxtConfig({
runtimeConfig: {
public: {
// These defaults will be overridden by NUXT_PUBLIC_SUPABASE_URL and
// NUXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY environment variables at runtime.
supabaseUrl: '',
supabasePublishableKey: '',
},
},
})SUPABASE_URL=supabase_project_url
SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keySUPABASE_URL=supabase_project_url
SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyInstall dotenv:
npm install dotenvyarn add dotenvpnpm add dotenvThen load the file before you read any variable from it. Put this on the first line of your entry point, above every other import:
require('dotenv').config()SUPABASE_URL=supabase_project_url
SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyVITE_SUPABASE_URL=supabase_project_url
VITE_SUPABASE_PUBLISHABLE_KEY=supabase_publishable_keyCreate a client
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.
Before you write code that checks who the user is, see Choosing an auth method.
Write utility functions to create Supabase clients [#nextjs-utility-functions]
To access Supabase from a Next.js app, you need 2 types of Supabase clients:
- Client Component client - To access Supabase from Client Components, which run in the browser.
- Server Component client - To access Supabase from Server Components, Server Actions, and Route Handlers, which run only on the server.
Since Next.js Server Components can't write cookies, you need a Proxy to refresh expired Auth tokens and store them.
Note
On Next.js 15 and earlier, a proxy.ts file is never called, so sessions never refresh and users get signed out. Next.js renamed this file in version 16. Before that, it's middleware.ts and the function is export async function middleware. The Supabase code inside it is the same either way.
The Proxy is responsible for:
- Refreshing the Auth token by calling
supabase.auth.getClaims(). - Passing the refreshed Auth token to Server Components, so they don't attempt to refresh the same token themselves. It is what keeps users signed in. This is accomplished with
request.cookies.set. - Passing the refreshed Auth token to the browser, so it replaces the old token. This is accomplished with
response.cookies.set.
What does the `cookies` object do?
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.
setAll is called whenever the library needs to write cookies, for example after a token refresh. It receives two arguments: the array of cookies to set, and a headers object containing the cache headers Cache-Control, Expires, and Pragma, which must be applied to the HTTP response to prevent CDNs from caching the response and leaking the session to other users. In the Proxy, apply these headers to the response. In Server Components, the headers cannot be set, which is why the setAll call is wrapped in a try/catch and the error is ignored. The Proxy handles writing cookies and headers on every request.
The cookie is named sb-<project_ref>-auth-token by default.
Do I need to create a new client for every route?
Yes! Creating a Supabase client is lightweight.
- On the server, it basically configures a
fetchcall. 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,
createBrowserClientalready uses a singleton pattern, so you only ever create one instance, no matter how many times you call yourcreateClientfunction.
Why does refreshing in two places sign users out?
A refresh token can generally be used only once, with two exceptions. Supabase allows a short window in which the same token can be presented again, which covers the normal SSR round trip. It also returns the active token when the parent of the active token is presented, which covers a client that never received the previous response. A reuse attempt that matches neither exception revokes the whole session.
This is hard to trace, because it looks like users being signed out at random rather than an error in your code.
Create a lib/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 lib utility functions for each client type.
import { createBrowserClient } from '@supabase/ssr'
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
)
}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, _headers) {
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 a proxy refreshing
// user sessions.
}
},
},
}
)
}Hook up proxy
The code adds a matcher so the Proxy doesn't run on routes that don't access Supabase.
Return the supabaseResponse object that setAll last built. An earlier response doesn't carry the refreshed cookies, so the user is signed out on the next request.
When you need to return a different response, copy the cookies and the cache headers onto it first:
const myNewResponse = NextResponse.next({ request })
myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
for (const header of ['cache-control', 'expires', 'pragma']) {
const value = supabaseResponse.headers.get(header)
if (value) myNewResponse.headers.set(header, value)
}
return myNewResponseDanger
Anyone can forge the session cookie, so trusting it without verification lets an attacker render another user's page. Always use supabase.auth.getClaims() to protect pages and user data.
Never trust supabase.auth.getSession() inside server code such as Proxy. It reads the session out of the cookie without revalidating it.
getClaims() verifies the token's signature on every call. On projects with asymmetric signing keys, the default for new projects, it verifies locally against a cached copy of the project's public keys. On projects still using a symmetric secret, it calls the Auth server instead. Either way the claims come from a token the server has verified rather than from whatever the cookie says.
import { type NextRequest } from 'next/server'
import { updateSession } from '@/lib/supabase/proxy'
export async function proxy(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)$).*)',
],
}import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
request,
})
// With Fluid compute, don't put this client in a global environment
// variable. Always create a new one on each 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, headers) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({
request,
})
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options)
)
Object.entries(headers).forEach(([key, value]) =>
supabaseResponse.headers.set(key, value)
)
},
},
}
)
// Do not run code between createServerClient and
// supabase.auth.getClaims(). A simple mistake could make it very hard to debug
// issues with users being randomly logged out.
// IMPORTANT: If you remove getClaims() and you use server-side rendering
// with the Supabase client, your users may be randomly logged out.
const { data } = await supabase.auth.getClaims()
const user = data?.claims
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
}Congratulations [#nextjs-congratulations]
To recap, you've:
- 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 Proxy to automatically refresh the Supabase Auth session.
You can now use any Supabase feature from your client or server code.
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.
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, headers) {
/**
* 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 `/`
* 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: '/' })
)
if (Object.keys(headers).length > 0) {
event.setHeaders(headers)
}
},
},
})
return resolve(event, {
filterSerializedResponseHeaders(name) {
return name === 'content-range' || name === 'x-supabase-api-version'
},
})
}To prevent TypeScript errors, add type definitions for the new event.locals properties.
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Database } from './database.types'
declare global {
namespace App {
// interface Error {}
interface Locals {
supabase: SupabaseClient<Database>
}
// interface PageState {}
// interface Platform {}
}
}
export {}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.
Page components can access the Supabase client from the data object using the load function.
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
},
},
})
/**
* `getClaims` validates the JWT signature locally (for asymmetric keys) once
* the relevant signing keys are available or cached, and returns the decoded
* claims. While an initial or periodic network request may be required to
* fetch or refresh keys, this is both faster and safer than `getSession`,
* which does not validate the JWT.
*/
const { data: claimsData, error } = await supabase.auth.getClaims()
const claims = error ? null : claimsData?.claims
return { supabase, claims }
}import type { LayoutServerLoad } from './$types'
export const load: LayoutServerLoad = async ({ cookies }) => {
return {
cookies: cookies.getAll(),
}
}Congratulations [#sveltekit-congratulations]
To recap, you've:
- 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 feature from your client or server code.
Configure Astro for SSR
Astro apps are static by default, so requests for data happen at build time rather than when a user requests a page. At build time there is no user, session, or cookie. Configure Astro for SSR if you want data fetched per request.
import { defineConfig } from 'astro/config'
export default defineConfig({
output: 'server',
})Create the Supabase clients [#astro-create-clients]
---
import { createServerClient, parseCookieHeader } from "@supabase/ssr";
const supabase = createServerClient(
import.meta.env.PUBLIC_SUPABASE_URL,
import.meta.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY,
{
cookies: {
getAll() {
return parseCookieHeader(Astro.request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, headers) {
cookiesToSet.forEach(({ name, value }) =>
Astro.cookies.set(name, value))
Object.entries(headers).forEach(([key, value]) =>
Astro.response.headers.set(key, value)
)
},
},
}
);
---<script>
import { createBrowserClient } from "@supabase/ssr";
const supabase = createBrowserClient(
import.meta.env.PUBLIC_SUPABASE_URL,
import.meta.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY
);
</script>import { createServerClient, parseCookieHeader } from '@supabase/ssr'
import type { APIContext } from 'astro'
export async function GET(context: APIContext) {
const responseHeaders = new Headers()
const supabase = createServerClient(
import.meta.env.PUBLIC_SUPABASE_URL,
import.meta.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY,
{
cookies: {
getAll() {
return parseCookieHeader(context.request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, headers) {
cookiesToSet.forEach(({ name, value }) => context.cookies.set(name, value))
Object.entries(headers).forEach(([key, value]) => responseHeaders.set(key, value))
},
},
}
)
// Build your response here, and pass `responseHeaders` to it. Without them a
// shared cache can store this response along with its Set-Cookie header.
return new Response(null, { headers: responseHeaders })
}
import { createServerClient, parseCookieHeader } from '@supabase/ssr'
import { defineMiddleware } from 'astro:middleware'
export const onRequest = defineMiddleware(async (context, next) => {
const responseHeaders = new Headers()
const supabase = createServerClient(
import.meta.env.PUBLIC_SUPABASE_URL,
import.meta.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY,
{
cookies: {
getAll() {
return parseCookieHeader(context.request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, headers) {
cookiesToSet.forEach(({ name, value }) => context.cookies.set(name, value))
Object.entries(headers).forEach(([key, value]) => responseHeaders.set(key, value))
},
},
}
)
const response = await next()
responseHeaders.forEach((value, key) => response.headers.set(key, value))
return response
})
Congratulations [#astro-congratulations]
To recap, you've:
- Created a server client for code that runs on the server, and a browser client for code that runs in the browser.
- Read and wrote the session cookie from a server endpoint and from middleware.
You can now use any Supabase feature from your client or server code.
Create the Supabase clients [#remix-create-clients]
With Remix, in a route module such as _index.tsx, you can export a loader, an action, and a default component.
Configure Supabase clients as follows:
- Create a server client in the
loader. Use it to load data and manage the user session on the server. Return your Supabase URL and publishable key so the browser can create a client. - Create a server client in the
action. Use it to handle form submissions and other mutations on the server. - Create a browser client in the default component. Call
useLoaderDatato read the URL and key, then callcreateBrowserClient.
The following example shows all three exports in one route module:
import { json, type ActionFunctionArgs, type LoaderFunctionArgs } from '@remix-run/node'
import { useLoaderData } from '@remix-run/react'
import {
createBrowserClient,
createServerClient,
parseCookieHeader,
serializeCookieHeader,
} from '@supabase/ssr'
// Server: load data and manage the user's session.
export async function loader({ request }: LoaderFunctionArgs) {
const responseHeaders = new Headers()
const supabase = createServerClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) =>
responseHeaders.append('Set-Cookie', serializeCookieHeader(name, value, options))
)
Object.entries(cacheHeaders).forEach(([key, value]) => responseHeaders.set(key, value))
},
},
}
)
// Use `supabase` here for server-side work, e.g. await supabase.auth.getClaims()
// Return the environment variables so the browser can create its own client.
return json(
{
env: {
SUPABASE_URL: process.env.SUPABASE_URL!,
SUPABASE_PUBLISHABLE_KEY: process.env.SUPABASE_PUBLISHABLE_KEY!,
},
},
{ headers: responseHeaders }
)
}
// Server: handle form submissions and mutations.
export async function action({ request }: ActionFunctionArgs) {
const responseHeaders = new Headers()
const supabase = createServerClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) =>
responseHeaders.append('Set-Cookie', serializeCookieHeader(name, value, options))
)
Object.entries(cacheHeaders).forEach(([key, value]) => responseHeaders.set(key, value))
},
},
}
)
return json(null, { headers: responseHeaders })
}
// Browser: create a client using the env vars returned by the loader.
export default function Index() {
const { env } = useLoaderData<typeof loader>()
const supabase = createBrowserClient(env.SUPABASE_URL, env.SUPABASE_PUBLISHABLE_KEY)
return <div>...</div>
}
Congratulations [#remix-congratulations]
To recap, you've:
- Created a server client in the
loaderto load data and manage the session. - Created a server client in the
actionto handle form submissions and mutations. - Created a browser client in the default component, using the values the
loaderreturned.
You can now use any Supabase feature from your client or server code.
Create the Supabase clients [#nuxt-create-clients]
import { createServerClient, parseCookieHeader, serializeCookieHeader } from '@supabase/ssr'
import { appendHeader, defineEventHandler, getHeader, setHeader } from 'h3'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const supabase = createServerClient(
config.public.supabaseUrl,
config.public.supabasePublishableKey,
{
cookies: {
getAll() {
return parseCookieHeader(getHeader(event, 'Cookie') ?? '')
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) => {
appendHeader(event, 'Set-Cookie', serializeCookieHeader(name, value, options))
})
Object.entries(cacheHeaders).forEach(([key, value]) => setHeader(event, key, value))
},
},
}
)
await supabase.auth.getClaims()
return { ok: true }
})
import { createBrowserClient } from '@supabase/ssr'
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig()
const supabase = createBrowserClient(
config.public.supabaseUrl,
config.public.supabasePublishableKey
)
return {
provide: {
supabase,
},
}
})Congratulations [#nuxt-congratulations]
To recap, you've:
- Created a server client in a server route for code that runs on the server.
- Created a browser client in a plugin for code that runs in the browser.
You can now use any Supabase feature from your client or server code.
Create the Supabase clients [#react-router-create-clients]
In React Router, a route module such as _index.tsx can export a loader, an action, and a default component. Create a server client inside the loader and action, and a browser client inside the component, passing the env vars through the loader.
import { data, type ActionFunctionArgs, type LoaderFunctionArgs } from 'react-router'
import { useLoaderData } from 'react-router'
import {
createBrowserClient,
createServerClient,
parseCookieHeader,
serializeCookieHeader,
} from '@supabase/ssr'
// Server: load data and manage the user's session.
export async function loader({ request }: LoaderFunctionArgs) {
const responseHeaders = new Headers()
const supabase = createServerClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) =>
responseHeaders.append('Set-Cookie', serializeCookieHeader(name, value, options))
)
Object.entries(cacheHeaders).forEach(([key, value]) => responseHeaders.set(key, value))
},
},
}
)
// Use `supabase` here for server-side work, e.g. await supabase.auth.getClaims()
// Return the env vars so the browser can create its own client.
return data(
{
env: {
SUPABASE_URL: process.env.SUPABASE_URL!,
SUPABASE_PUBLISHABLE_KEY: process.env.SUPABASE_PUBLISHABLE_KEY!,
},
},
{ headers: responseHeaders }
)
}
// Server: handle form submissions and mutations.
export async function action({ request }: ActionFunctionArgs) {
const responseHeaders = new Headers()
const supabase = createServerClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return parseCookieHeader(request.headers.get('Cookie') ?? '')
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) =>
responseHeaders.append('Set-Cookie', serializeCookieHeader(name, value, options))
)
Object.entries(cacheHeaders).forEach(([key, value]) => responseHeaders.set(key, value))
},
},
}
)
return data(null, { headers: responseHeaders })
}
// Browser: create a client using the env vars returned by the loader.
export default function Index() {
const { env } = useLoaderData<typeof loader>()
const supabase = createBrowserClient(env.SUPABASE_URL, env.SUPABASE_PUBLISHABLE_KEY)
return <div>...</div>
}
Congratulations [#react-router-congratulations]
To recap, you've:
- Created a server client in the
loaderand theaction. - Created a browser client in the default component, using the values the
loaderreturned.
You can now use any Supabase feature from your client or server code.
Create the Supabase clients [#express-create-clients]
const { createServerClient, parseCookieHeader, serializeCookieHeader } = require('@supabase/ssr')
exports.createClient = (context) => {
return createServerClient(process.env.SUPABASE_URL, process.env.SUPABASE_PUBLISHABLE_KEY, {
cookies: {
getAll() {
return parseCookieHeader(context.req.headers.cookie ?? '')
},
setAll(cookiesToSet, headers) {
cookiesToSet.forEach(({ name, value }) =>
context.res.appendHeader('Set-Cookie', serializeCookieHeader(name, value))
)
Object.entries(headers).forEach(([key, value]) => context.res.setHeader(key, value))
},
},
})
}
require("dotenv").config()
const express = require("express")
const { createClient } = require("./lib/supabase")
const app = express()
app.post("/hello-world", async function (req, res, next) {
const { email, emailConfirm } = req.body
...
const supabase = createClient({ req, res })
})
Congratulations [#express-congratulations]
To recap, you've:
- Created a request-specific server client.
- Used that client in a route to make authenticated requests.
You can now use any Supabase feature from your client or server code.
Create the Supabase clients [#hono-create-clients]
Create a Hono middleware that creates a Supabase client.
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 type { CookieOptions } from 'hono/utils/cookie'
import type { Database } from '../database.types'
declare module 'hono' {
interface ContextVariableMap {
supabase: SupabaseClient<Database>
}
}
export const getSupabase = (c: Context) => {
return c.get('supabase')
}
type SupabaseEnv = {
VITE_SUPABASE_URL: string
VITE_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_PUBLISHABLE_KEY ?? import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
if (!supabaseUrl) {
throw new Error('VITE_SUPABASE_URL missing!')
}
if (!supabasePublishableKey) {
throw new Error('VITE_SUPABASE_PUBLISHABLE_KEY missing!')
}
const supabase = createServerClient(supabaseUrl, supabasePublishableKey, {
cookies: {
getAll() {
return parseCookieHeader(c.req.header('Cookie') ?? '')
},
setAll(cookiesToSet, cacheHeaders) {
cookiesToSet.forEach(({ name, value, options }) =>
setCookie(c, name, value, options as CookieOptions)
)
Object.entries(cacheHeaders).forEach(([key, value]) => c.header(key, value))
},
},
})
c.set('supabase', supabase)
await next()
}
}
You can now use this middleware in your Hono application to create a server Supabase client that can be used to make authenticated requests.
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { getSupabase, supabaseMiddleware } from './middleware/auth.middleware'
const app = new Hono()
app.use('*', csrf())
app.use('*', supabaseMiddleware())
const routes = app.get('/api/user', async (c) => {
const supabase = getSupabase(c)
const { data, error } = await supabase.auth.getClaims()
if (error) console.log('error', error)
if (!data?.claims) {
return c.json({
message: 'You are not logged in.',
})
}
return c.json({
message: 'You are logged in!',
userId: data.claims.sub,
})
})
app.post('/signout', async (c) => {
const supabase = getSupabase(c)
await supabase.auth.signOut()
console.log('Signed out server-side!')
return c.redirect('/', 303)
})
app.get('/instruments', async (c) => {
const supabase = getSupabase(c)
const { data, error } = await supabase.from('instruments').select('*')
if (error) {
console.error(error)
return c.json({ error: error.message }, 500)
}
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
Congratulations [#hono-congratulations]
To recap, you've:
- Created a Hono middleware that builds a request-specific server client.
- Used that client in a route to make authenticated requests.
You can now use any Supabase feature from your client or server code.
Write utility functions to create Supabase clients [#tanstack-utility-functions]
TanStack Start renders matched routes on the server by default, so beforeLoad and loader run server-side on the initial request. Unlike Next.js, this means you don't need a proxy or middleware layer to keep sessions fresh. The server client reads and writes the session cookie directly on each request.
Create a lib/supabase folder at the root of your project, or inside the ./src folder if you are using one, then add a file for each type of client:
- Create a browser client in
lib/supabase/client.ts. Use it to access Supabase from components that run in the browser. - Create a server client in
lib/supabase/server.ts. Use it to access Supabase from loaders, server functions, and other code that runs only on the server.
Copy the lib utility functions below into each file:
/// <reference types="vite/types/importMeta.d.ts" />
import { createBrowserClient } from '@supabase/ssr'
export function createClient() {
return createBrowserClient(
import.meta.env.VITE_SUPABASE_URL!,
import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY!
)
}
import { createServerClient } from '@supabase/ssr'
import { getCookies, setCookie, setResponseHeader } from '@tanstack/react-start/server'
export function createClient() {
return createServerClient(
process.env.VITE_SUPABASE_URL!,
process.env.VITE_SUPABASE_PUBLISHABLE_KEY!,
{
cookies: {
getAll() {
return Object.entries(getCookies()).map(
([name, value]) =>
({
name,
value,
}) as { name: string; value: string }
)
},
setAll(cookies, headers) {
cookies.forEach(({ name, value, options }) => {
setCookie(name, value, options)
})
Object.entries(headers).forEach(([name, value]) => {
setResponseHeader(name, value)
})
},
},
}
)
}
Protecting routes
TanStack Start has no global middleware layer, so protect each route explicitly.
To protect your routes:
- Write a server function,
fetchClaims, that callssupabase.auth.getClaims()and returns the claims, ornullif the session isn't valid. - Call
fetchClaimsfrom a layout route'sbeforeLoadhook, such as_protected.tsx, before any nested route renders. Redirect to/loginwhen it returnsnull.
Danger
Skipping the check inside the server function exposes private data to unauthenticated users. beforeLoad runs on the server for the initial request and on the client for later navigation, but either way it only gates the route's render. It doesn't stop the server function from being called directly. Because there's no proxy re-checking every request, the server function is the only checkpoint that always runs, so it must call supabase.auth.getClaims() to authorize the request itself.
getClaims() validates the JWT signature on every call, the same check the Next.js Proxy relies on. Calling it inside the server function gives TanStack Start's per-route check that same guarantee, because the function runs on every request to a protected route.
import { createServerFn } from '@tanstack/react-start'
import { createClient } from '@/lib/supabase/server'
export const fetchClaims = createServerFn({ method: 'GET' }).handler(async () => {
const supabase = createClient()
const { data, error } = await supabase.auth.getClaims()
if (error) {
return null
}
return data.claims
})
import { createFileRoute, redirect } from '@tanstack/react-router'
import { fetchClaims } from '@/lib/supabase/fetch-claims-server-fn'
export const Route = createFileRoute('/_protected')({
beforeLoad: async () => {
const claims = await fetchClaims()
if (!claims) {
throw redirect({ to: '/login' })
}
return {
claims,
}
},
})
Any other server function that returns or mutates private data needs this same check. Don't rely on a route being nested under _protected alone.
Congratulations [#tanstack-congratulations]
To recap, you've:
- Set up a Supabase client utility to call Supabase from a browser component. You can use this if you need to call Supabase from the browser, for example to set up a realtime subscription.
- Set up a server client utility to call Supabase from loaders and server functions.
- Protected a route with
beforeLoad, backed by a server function that authorizes the request itself.
You can now use any Supabase feature from your client or server code.
Choosing an auth method
The Supabase Auth SDK contains three different functions for authenticating user access to applications:
Summary of the methods
- Use
getClaimsto protect pages and user data. It reads the access token from storage and verifies it. Locally via the WebCrypto API and a cached JWKS endpoint when the project uses asymmetric signing keys (the default for new projects), or by callinggetUsersolely to validate when symmetric keys are in use. The returned claims always come from decoding the JWT, not from a user lookup. When the access token is close to expiring,getClaimsrefreshes the session before it verifies, which is how a server-rendered session stays alive. getUsermakes a network call to the project's Auth instance to get the user record, which includes the most up-to-date information about the user at the cost of a network call.getSessionwhen you need the raw session (the access token, refresh token, and expiry). For example to forward the access token to another service. The session is loaded directly from local storage and isn't re-validated against the Auth server, so the embedded user object shouldn't be trusted on its own when storage is shared with the client (cookies, request headers). To verify identity, validate the access token withgetClaims, or callgetUserfor a fresh, server-confirmed user record.
In summary: use getClaims to verify identity (typically for protecting pages and data), getUser when you need an up-to-date user record from the Auth server, and getSession when you need the access or refresh token directly, but don't rely on the user object it returns for authorization decisions.
Caching considerations
If your app uses ISR (Incremental Static Regeneration) or is deployed behind a CDN, caching of HTTP responses can cause users to receive another user's session. When a session is refreshed, the new token is written to the response via Set-Cookie. If that response is cached and served to a different user, that user will be signed in as the wrong person.
See the advanced Auth server-side rendering guide for details and framework-specific examples.
Next steps
- Implement Authentication using Email and Password
- Implement Authentication using OAuth
- Learn more about SSR