Supabase Clients

Using Supabase with different clients

Before diving into the various ways we can communicate with the server, we need to introduce how we communicate with Supabase, which is hosting the database and therefore the source of our data.

Depending on where your code runs, you may need to use different clients to interact with Supabase. This is due to how cookies are set differently in various parts of the Next.js application.

You can use 4 different clients to interact with Supabase:

  1. Browser - This runs in the browser and is used to interact with Supabase from the client
  2. Server Actions - This runs in Server Actions and is used to interact with Supabase from the server
  3. Route Handlers - This runs in Route Handlers and is used to interact with Supabase from the server
  4. Server Components - This runs in Server Components and is used to interact with Supabase from the server

Browser

To use the browser client, use the useSupabase hook:

import { useSupabase } from '@kit/supabase/hooks/use-supabase'; export default function Home() { const supabase = useSupabase() return ( <div> <h1>Supabase Browser Client</h1> <button onClick={() => supabase.auth.signOut()}>Sign Out</button> </div> ) }

Server Actions

To use the server actions client, use the useSupabase hook:

'use server'; import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client'; export async function myServerAction() { const supabase = getSupabaseServerActionClient(); const { data, error } = await supabase.from('users').select('*') return { success: true, }; }

Route Handlers

To use the route handlers client, use the getSupabaseRouteHandlerClient function:

import { NextRequest, NextResponse } from 'next/server'; import { getSupabaseRouteHandlerClient } from '@kit/supabase/route-handlers-client'; export async function POST(req: NextRequest) { const supabase = getSupabaseRouteHandlerClient(); const { data, error } = await supabase.from('users').select('*') return NextResponse.json({ data }); }

Server Components

To use the server components client, use the getSupabaseServerComponentClient function:

import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client'; export default async function TasksPage() { const supabase = getSupabaseServerComponentClient(); const { data, error } = await supabase.from('users').select('*'); return <TasksList tasks={data} /> }

Subscribe to our Newsletter
Get the latest updates about React, Remix, Next.js, Firebase, Supabase and Tailwind CSS