Supabase Auth using @supabase/ssr

November 23, 2023

Supabase is a powerful open-source alternative to traditional PostgreSQL databases that offers a compelling set of features for free users. Built on top of PostgreSQL, Supabase allows users to explore and experiment with a modern and feature-rich database solution without the usual financial constraints, which makes it appealing for hobbyists.

Supabase has introduced the latest @supabase/ssr for auth which replaces the @supabase/auth-helpers-nextjs, and ah yes we are using Next js for this project.

So the thing about SSR frameworks is that they render components in the server side, and in Supabase we use cookies to authenticate the user, all in the server by passing along that cookie stored in the client side to the server side in the request header. This is how I understand whats happening under the hood.

So whenever a server side rendering happens, the cookie is passed to the server and it is rendered, in my opinion this eliminates the use of useEffect and useState in some scenarios.

The important part is to create seperate clients for server and client sides, keep them seperate.

This is how to set up the client side client

"use client";

import { createBrowserClient } from '@supabase/ssr'export default function CreateSupabaseBrowserClient () { return createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! )}

This is how to setup the server side client

import { createServerClient, type CookieOptions } from '@supabase/ssr'import { cookies } from 'next/headers'export default async function Page () { const cookieStore = cookies() return createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { get(name: string) { return cookieStore.get(name)?.value }, }, } )}

And after setting these two properly, I suggest you should set up RLS in the relations and give appropriate access to different roles accordingly.

Then you can simply create a supabase client using, const supabase = await CreateSupabaseServerClient(); and use the supabase-js client to fetch data from the server.