Skip to content

Overview

import { createClient } from "@supabase/supabase-js";

export const createSupabaseClient = () =>
  createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
  );

At this point, you have a function called createSupabaseClient() that initializes a new Supabase client with the given values. This function can now be imported from any other file.


Utilizing createBrowserClient on the frontend

Let’s start by solving the frontend problem first and then go back and re-evaluate the details of the backend problem.

Here, @supabase/supabase-js is always the base package that you install in any JavaScript-based environment where you use the Supabase JavaScript client. Then, there is a complementary package from Supabase called @supabase/ssr. It is framework-independent but wraps functionality to make cookie management easy on both the frontend and backend so that you can log in on the frontend and use the authentication on the backend and vice versa. We’ll use the package to create a frontend Supabase client.

Although ssr stands for server-side rendering, it comes packed with a function called createBrowserClient, which solves our first problem, recreation: it is a wrapper on top of the createClient function from @supabase/supabase-js and uses a Singleton pattern. So, you can call it as often as you want, and the client is still just created once.

To use it, first, install the package with npm install @supabase/ssr. Then, go to your supabase-utils/client.js file. Here, you will see the following code:

import { createClient } from "@supabase/supabase-js";

export const createSupabaseClient = () => createClient(...);

Now, replace createClient with the createBrowserClient import, as follows:

import { createBrowserClient } from "@supabase/ssr";

export const createSupabaseClient = () =>
createBrowserClient(...);

This would be sufficient, but I want to do two more things to add more clarity that this is about the frontend:

  1. First, rename createSupabaseClient to getSupabaseBrowserClient so that it looks like this:

    import { createBrowserClient } from "@supabase/ssr";
    export const getSupabaseBrowserClient = () =>
    createBrowserClient(...);
    

    Just by changing the name, it’s clearer that we aren’t recreating the client all the time and that we’re supposed to use this on the frontend.

  2. Second, rename client.js to browserClient.js as this name provides more details about what it is – that is, a browser-targeted Supabase client. Don’t forget to adapt your existing createSupabaseClient imports so that they match the name changes.

With that, problem one has been solved. Now, let’s get back to problem two – the backend.


Reference