#Supabase SSR

1 messages · Page 1 of 1 (latest)

hybrid turtle
#

Supabase/ssr package docs have this:

import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'

export function createClient() {
  const cookieStore = cookies()

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll()
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            )
          } catch {
            // The `setAll` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
      },
    }
  )
}

It makes all server side clients use cookies so it opts out of caching.
Is it okay to use that like this or should i change it

gritty shaleBOT
#

Hi @hybrid turtle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The code you provided is a common way to set up Supabase with Server Side Rendering (SSR) in Next.js. It creates a Supabase client that uses cookies for authentication, which is necessary for user-specific data.

However, there are a few things to consider:

  1. Global vs Local Scope: According to the discussions in the Github issue (https://github.com/vercel/next.js/issues/67191), it's recommended to call createClient() inside the functions where it's used, rather than declaring it globally. This is because calling createClient() outside of a function scope can lead to issues, as it might be called outside a request scope.

  2. Unit Testing: If you're planning to do unit testing with a tool like Jest, you might run into issues because cookies aren't available in that environment. This was mentioned in the Github issue (https://github.com/vercel/next.js/issues/67191) but no solution was provided.

  3. Caching: As you mentioned, using cookies opts out of caching. This is a trade-off you have to consider. If your application relies heavily on user-specific data and needs to authenticate users on the server-side, using cookies might be necessary. However, if you can authenticate users on the client-side and your server-rendered pages are not user-specific, you might be able to benefit from caching.

Remember to replace process.env.NEXT_PUBLIC_SUPABASE_URL and process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY with your actual Supabase URL and anonymous key.

In conclusion, the way you're using createClient() seems to be correct for a typical SSR setup with Supabase in Next.js, but you should be aware of the trade-offs and potential issues.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: