is this secure

I’m creating two server-side Supabase clients in Next.js:

  • One “clean” client that isn’t affected by cookies to use the service role key.
  • One client that uses cookies for normal user sessions.
Both clients run only server-side. Is this the correct approach to safely leverage the service role key while handling user sessions?

import { Database } from "@/src/types/database-types";
import { createServerClient } from "@supabase/ssr";
import { SupabaseClient } from "@supabase/supabase-js";
import { cookies } from "next/headers";

/**
 * Creates a Supabase client for server-side use.
 * @returns A Supabase client instance.
 */
export async function createServerSupabaseClient(): Promise<
  SupabaseClient<Database>
> {
  // Deprecation is only regarding the cookie methods, not the function itself
  return createServerClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    {
      cookies: {
        getAll() {
          return [];
        },
        setAll() {},
      },
    }
  );
}

async function createAnonymousServerSupabaseClient() {
  const cookieStore = await cookies();
  return createServerClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_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.
          }
        },
      },
    }
  );
}
Was this page helpful?