Skip to content

serverSupabaseServiceRole(event) make "event" argument optional #563

@Kiansa

Description

@Kiansa

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions