Auth

Creating a Supabase client for SSR

Configure your Supabase client to use cookies


To use Server-Side Rendering (SSR) with Supabase, you need to configure your Supabase client to use cookies. The @supabase/ssr package helps you do this for JavaScript/TypeScript applications.

Install

Install the @supabase/ssr and @supabase/supabase-js packages:

1
npm install @supabase/ssr @supabase/supabase-js

Set environment variables

In your environment variables file, set your Supabase URL and Supabase Anon Key:

Project URL
Anon key
1
2
SUPABASE_URL=your_supabase_project_urlSUPABASE_ANON_KEY=your_supabase_anon_key

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.

Use the browser client in code that runs on the browser, and the server client in code that runs on the server.

Create a Hono middleware that creates a Supabase client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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'declare module 'hono' { interface ContextVariableMap { supabase: SupabaseClient }}export const getSupabase = (c: Context) => { return c.get('supabase')}type SupabaseEnv = { SUPABASE_URL: string SUPABASE_ANON_KEY: string}export const supabaseMiddleware = (): MiddlewareHandler => { return async (c, next) => { const supabaseEnv = env<SupabaseEnv>(c) const supabaseUrl = supabaseEnv.SUPABASE_URL const supabaseAnonKey = supabaseEnv.SUPABASE_ANON_KEY if (!supabaseUrl) { throw new Error('SUPABASE_URL missing!') } if (!supabaseAnonKey) { throw new Error('SUPABASE_ANON_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() }}

Next steps