supabase icon indicating copy to clipboard operation
supabase copied to clipboard

serverSupabaseServiceRole(event) make "event" argument optional

Open Kiansa opened this issue 1 month ago • 0 comments

I use serverSupabaseServiceRole() a lot on my server/utils and there is no need for the h3 event to be passed in most cases.

here is what ai suggests:

// src/runtime/server/services/serverSupabaseServiceRole.ts

import type { SupabaseClient } from '@supabase/supabase-js'
import { createClient } from '@supabase/supabase-js'
import { fetchWithRetry } from '../../utils/fetch-retry'
import type { H3Event } from 'h3'
import { useRuntimeConfig } from '#imports'
// @ts-expect-error - `#supabase/database` is a runtime alias
import type { Database } from '#supabase/database'
import type { ModuleOptions } from '../../../module'

export const serverSupabaseServiceRole = <T = Database = Database>(
  event?: H3Event
): SupabaseClient<T> => {
  const config = useRuntimeConfig(event)

  const url = config.public.supabase.url
  const secretKey = (config.supabase as ModuleOptions).secretKey
  const serviceKey = (config.supabase as ModuleOptions).serviceKey

  const serverKey = secretKey || serviceKey

  if (!serverKey) {
    throw new Error(
      'Missing server key. Set either `SUPABASE_SECRET_KEY` (recommended) or `SUPABASE_SERVICE_KEY` (deprecated) in your environment variables.'
    )
  }

  // Use request context if event exists, otherwise fall back to globalThis (shared instance)
  const context = (event?.context ?? globalThis) as any

  if (!context._supabaseServiceRole) {
    context._supabaseServiceRole = createClient<T>(url, serverKey, {
      auth: {
        detectSessionInUrl: false,
        persistSession: false,
        autoRefreshToken: false,
      },
      global: {
        fetch: fetchWithRetry,
      },
    })
  }

  return context._supabaseServiceRole
}

Kiansa avatar Dec 06 '25 17:12 Kiansa