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:
1npm 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
12SUPABASE_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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import { 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
- Implement Authentication using Email and Password
- Implement Authentication using OAuth
- Learn more about SSR