Fix Supabase connection issues with lazy initialization and enhanced logging

This commit is contained in:
Marco Gallegos
2026-01-18 09:15:26 -06:00
parent 0b13b991c9
commit a6902b6b46
5 changed files with 271 additions and 117 deletions

View File

@@ -1,5 +1,5 @@
# Dockerfile optimizado para Next.js production # Dockerfile optimizado para Next.js production
FROM node:18-alpine AS base FROM node:20-alpine AS base
# Instalar dependencias para build # Instalar dependencias para build
FROM base AS deps FROM base AS deps

View File

@@ -6,11 +6,24 @@ import { supabase } from '@/lib/supabase/client'
*/ */
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
try { try {
console.log('=== LOCATIONS API START ===')
console.log('Locations API called with URL:', request.url) console.log('Locations API called with URL:', request.url)
// Check Supabase connection // Test basic fetch to Supabase URL
console.log('Supabase URL:', process.env.NEXT_PUBLIC_SUPABASE_URL) const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
console.log('Supabase key exists:', !!process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY) console.log('Testing basic connectivity to Supabase...')
try {
const testResponse = await fetch(`${supabaseUrl}/rest/v1/`, {
method: 'GET',
headers: {
'apikey': process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '',
'Content-Type': 'application/json'
}
})
console.log('Basic Supabase connectivity test:', testResponse.status, testResponse.statusText)
} catch (fetchError) {
console.error('Basic fetch test failed:', fetchError)
}
console.log('Executing locations query...') console.log('Executing locations query...')
const { data: locationsData, error: queryError } = await supabase const { data: locationsData, error: queryError } = await supabase
@@ -19,7 +32,7 @@ export async function GET(request: NextRequest) {
.eq('is_active', true) .eq('is_active', true)
.order('name', { ascending: true }) .order('name', { ascending: true })
console.log('Query result - data:', !!locationsData, 'error:', !!queryError) console.log('Query result - data exists:', !!locationsData, 'error exists:', !!queryError)
if (queryError) { if (queryError) {
console.error('Locations GET error details:', { console.error('Locations GET error details:', {
@@ -32,25 +45,31 @@ export async function GET(request: NextRequest) {
{ {
error: queryError.message, error: queryError.message,
code: queryError.code, code: queryError.code,
details: queryError.details details: queryError.details,
timestamp: new Date().toISOString()
}, },
{ status: 500 } { status: 500 }
) )
} }
console.log('Locations found:', locationsData?.length || 0) console.log('Locations found:', locationsData?.length || 0)
console.log('=== LOCATIONS API END ===')
return NextResponse.json({ return NextResponse.json({
success: true, success: true,
locations: locationsData || [], locations: locationsData || [],
count: locationsData?.length || 0 count: locationsData?.length || 0,
timestamp: new Date().toISOString()
}) })
} catch (error) { } catch (error) {
console.error('=== LOCATIONS API ERROR ===')
console.error('Locations GET unexpected error:', error) console.error('Locations GET unexpected error:', error)
console.error('Error stack:', error instanceof Error ? error.stack : 'Unknown error') console.error('Error stack:', error instanceof Error ? error.stack : 'Unknown error')
console.error('Error type:', error instanceof Error ? error.constructor.name : typeof error)
return NextResponse.json( return NextResponse.json(
{ {
error: 'Internal server error', error: 'Internal server error',
details: error instanceof Error ? error.message : 'Unknown error' details: error instanceof Error ? error.message : 'Unknown error',
timestamp: new Date().toISOString()
}, },
{ status: 500 } { status: 500 }
) )

View File

@@ -6,15 +6,28 @@ import { supabase } from '@/lib/supabase/client'
*/ */
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
try { try {
console.log('=== SERVICES API START ===')
console.log('Services API called with URL:', request.url) console.log('Services API called with URL:', request.url)
const { searchParams } = new URL(request.url) const { searchParams } = new URL(request.url)
const locationId = searchParams.get('location_id') const locationId = searchParams.get('location_id')
console.log('Location ID filter:', locationId) console.log('Location ID filter:', locationId)
// Check Supabase connection // Test basic fetch to Supabase URL
console.log('Supabase URL:', process.env.NEXT_PUBLIC_SUPABASE_URL) const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
console.log('Supabase key exists:', !!process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY) console.log('Testing basic connectivity to Supabase...')
try {
const testResponse = await fetch(`${supabaseUrl}/rest/v1/`, {
method: 'GET',
headers: {
'apikey': process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '',
'Content-Type': 'application/json'
}
})
console.log('Basic Supabase connectivity test:', testResponse.status, testResponse.statusText)
} catch (fetchError) {
console.error('Basic fetch test failed:', fetchError)
}
let query = supabase let query = supabase
.from('services') .from('services')
@@ -26,10 +39,10 @@ export async function GET(request: NextRequest) {
query = query.eq('location_id', locationId) query = query.eq('location_id', locationId)
} }
console.log('Executing query...') console.log('Executing Supabase query...')
const { data: servicesData, error: queryError } = await query const { data: servicesData, error: queryError } = await query
console.log('Query result - data:', !!servicesData, 'error:', !!queryError) console.log('Query result - data exists:', !!servicesData, 'error exists:', !!queryError)
if (queryError) { if (queryError) {
console.error('Services GET error details:', { console.error('Services GET error details:', {
@@ -42,25 +55,31 @@ export async function GET(request: NextRequest) {
{ {
error: queryError.message, error: queryError.message,
code: queryError.code, code: queryError.code,
details: queryError.details details: queryError.details,
timestamp: new Date().toISOString()
}, },
{ status: 500 } { status: 500 }
) )
} }
console.log('Services found:', servicesData?.length || 0) console.log('Services found:', servicesData?.length || 0)
console.log('=== SERVICES API END ===')
return NextResponse.json({ return NextResponse.json({
success: true, success: true,
services: servicesData || [], services: servicesData || [],
count: servicesData?.length || 0 count: servicesData?.length || 0,
timestamp: new Date().toISOString()
}) })
} catch (error) { } catch (error) {
console.error('=== SERVICES API ERROR ===')
console.error('Services GET unexpected error:', error) console.error('Services GET unexpected error:', error)
console.error('Error stack:', error instanceof Error ? error.stack : 'Unknown error') console.error('Error stack:', error instanceof Error ? error.stack : 'Unknown error')
console.error('Error type:', error instanceof Error ? error.constructor.name : typeof error)
return NextResponse.json( return NextResponse.json(
{ {
error: 'Internal server error', error: 'Internal server error',
details: error instanceof Error ? error.message : 'Unknown error' details: error instanceof Error ? error.message : 'Unknown error',
timestamp: new Date().toISOString()
}, },
{ status: 500 } { status: 500 }
) )

View File

@@ -4,7 +4,7 @@ import { useState, useEffect } from 'react'
import { AnimatedLogo } from '@/components/animated-logo' import { AnimatedLogo } from '@/components/animated-logo'
import { RollingPhrases } from '@/components/rolling-phrases' import { RollingPhrases } from '@/components/rolling-phrases'
/** @description Services page with home page style structure */ /** @description Premium services page with elegant layout and sophisticated design */
interface Service { interface Service {
id: string id: string
@@ -57,22 +57,35 @@ export default function ServiciosPage() {
const getCategoryTitle = (category: string) => { const getCategoryTitle = (category: string) => {
const titles: Record<string, string> = { const titles: Record<string, string> = {
core: 'CORE EXPERIENCES - El corazón de Anchor 23', core: 'CORE EXPERIENCES',
nails: 'NAIL COUTURE - Técnica invisible. Resultado impecable.', nails: 'NAIL COUTURE',
hair: 'HAIR FINISHING RITUALS', hair: 'HAIR FINISHING RITUALS',
lashes: 'LASH & BROW RITUALS - Mirada definida con sutileza.', lashes: 'LASH & BROW RITUALS',
brows: 'LASH & BROW RITUALS - Mirada definida con sutileza.', brows: 'LASH & BROW RITUALS',
events: 'EVENT EXPERIENCES - Agenda especial', events: 'EVENT EXPERIENCES',
permanent: 'PERMANENT RITUALS - Agenda limitada · Especialista certificada' permanent: 'PERMANENT RITUALS'
} }
return titles[category] || category return titles[category] || category
} }
const getCategorySubtitle = (category: string) => {
const subtitles: Record<string, string> = {
core: 'El corazón de Anchor 23',
nails: 'Técnica invisible. Resultado impecable.',
hair: 'Disponibles únicamente para clientas con experiencia Anchor el mismo día',
lashes: 'Mirada definida con sutileza',
brows: 'Mirada definida con sutileza',
events: 'Agenda especial',
permanent: 'Agenda limitada · Especialista certificada'
}
return subtitles[category] || ''
}
const getCategoryDescription = (category: string) => { const getCategoryDescription = (category: string) => {
const descriptions: Record<string, string> = { const descriptions: Record<string, string> = {
core: 'Rituales conscientes donde el tiempo se desacelera. Cada experiencia está diseñada para mujeres que valoran el silencio, la atención absoluta y los resultados impecables.', core: 'Rituales conscientes donde el tiempo se desacelera. Cada experiencia está diseñada para mujeres que valoran el silencio, la atención absoluta y los resultados impecables.',
nails: 'En Anchor 23 no eliges técnicas. Cada decisión se toma internamente para lograr un resultado elegante, duradero y natural. No ofrecemos servicios de mantenimiento ni correcciones.', nails: 'En Anchor 23 no eliges técnicas. Cada decisión se toma internamente para lograr un resultado elegante, duradero y natural. No ofrecemos servicios de mantenimiento ni correcciones.',
hair: 'Disponibles únicamente para clientas con experiencia Anchor el mismo día.', hair: '',
lashes: '', lashes: '',
brows: '', brows: '',
events: 'Agenda especial para ocasiones selectas.', events: 'Agenda especial para ocasiones selectas.',
@@ -93,10 +106,10 @@ export default function ServiciosPage() {
if (loading) { if (loading) {
return ( return (
<div className="section"> <div className="min-h-screen flex items-center justify-center">
<div className="section-header"> <div className="text-center">
<h1 className="section-title">Nuestros Servicios</h1> <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-charcoal-brown mb-4"></div>
<p className="section-subtitle">Cargando servicios...</p> <p className="text-xl text-charcoal-brown opacity-70">Cargando servicios...</p>
</div> </div>
</div> </div>
) )
@@ -104,94 +117,152 @@ export default function ServiciosPage() {
return ( return (
<> <>
<section className="hero"> {/* Hero Section - Simplified and Elegant */}
<div className="hero-content"> <section className="relative min-h-[60vh] flex items-center justify-center pt-32 pb-20 overflow-hidden">
<AnimatedLogo /> {/* Background Pattern */}
<h1>Servicios</h1> <div className="absolute inset-0 opacity-30">
<h2>Anchor:23</h2> <div className="absolute inset-0" style={{
<RollingPhrases /> backgroundImage: `radial-gradient(circle at 2px 2px, rgba(111, 94, 79, 0.15) 1px, transparent 0)`,
<div className="hero-actions"> backgroundSize: '40px 40px'
<a href="/booking/servicios" className="btn-primary"> }}></div>
Reservar Cita </div>
<div className="relative z-10 max-w-5xl mx-auto px-8 text-center">
<div className="mb-8">
<AnimatedLogo />
</div>
<h1 className="text-6xl md:text-8xl font-bold mb-6 tracking-tight" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
Nuestros Servicios
</h1>
<div className="mb-10">
<RollingPhrases />
</div>
<p className="text-xl md:text-2xl mb-12 max-w-3xl mx-auto leading-relaxed opacity-80" style={{ color: 'var(--charcoal-brown)' }}>
Experiencias diseñadas para mujeres que valoran el silencio, la atención absoluta y los resultados impecables.
</p>
<div className="flex items-center justify-center gap-6">
<a href="/booking/servicios" className="btn-primary text-base px-10 py-4">
Reservar Experiencia
</a> </a>
</div> </div>
</div> </div>
<div className="hero-image"> </section>
<div className="w-full h-96 flex items-center justify-center bg-gradient-to-br from-amber-50 to-gray-50">
<span className="text-gray-500 text-lg">Imagen Servicios</span> {/* Philosophy Section */}
<section className="py-24 relative" style={{ background: 'var(--soft-cream)' }}>
<div className="max-w-6xl mx-auto px-8">
<div className="grid md:grid-cols-2 gap-16 items-center">
<div>
<p className="text-sm font-semibold tracking-widest uppercase mb-4 opacity-60" style={{ color: 'var(--deep-earth)' }}>
Nuestra Filosofía
</p>
<h2 className="text-4xl md:text-5xl font-bold mb-6 leading-tight" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
Criterio antes que cantidad
</h2>
<p className="text-lg leading-relaxed mb-6 opacity-85" style={{ color: 'var(--charcoal-brown)' }}>
Anchor 23 es un espacio privado donde el tiempo se desacelera. Aquí, cada experiencia está diseñada para mujeres que valoran el silencio, la atención absoluta y los resultados impecables.
</p>
<p className="text-lg leading-relaxed font-medium" style={{ color: 'var(--deep-earth)' }}>
No trabajamos con volumen. Trabajamos con intención.
</p>
</div>
<div className="relative h-96 rounded-2xl overflow-hidden shadow-2xl">
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-amber-100 via-stone-100 to-neutral-100">
<span className="text-neutral-400 text-lg font-light">Imagen Experiencias</span>
</div>
</div>
</div> </div>
</div> </div>
</section> </section>
<section className="foundation"> {/* Services Catalog */}
<article> <section className="py-32" style={{ background: 'var(--bone-white)' }}>
<h3>Experiencias</h3> <div className="max-w-7xl mx-auto px-8">
<h4>Criterio antes que cantidad</h4>
<p>
Anchor 23 es un espacio privado donde el tiempo se desacelera. Aquí, cada experiencia está diseñada para mujeres que valoran el silencio, la atención absoluta y los resultados impecables.
</p>
<p>
No trabajamos con volumen. Trabajamos con intención.
</p>
</article>
<aside className="foundation-image">
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-amber-50 to-gray-50">
<span className="text-gray-500 text-lg">Imagen Experiencias</span>
</div>
</aside>
</section>
<section className="services-preview">
<h3>Nuestros Servicios</h3>
<div className="max-w-7xl mx-auto px-6">
{categoryOrder.map(category => { {categoryOrder.map(category => {
const categoryServices = groupedServices[category] const categoryServices = groupedServices[category]
if (!categoryServices || categoryServices.length === 0) return null if (!categoryServices || categoryServices.length === 0) return null
return ( return (
<div key={category} className="service-cards mb-24"> <div key={category} className="mb-32 last:mb-0">
<div className="mb-8"> {/* Category Header */}
<h4 className="text-3xl font-bold text-gray-900 mb-4"> <div className="mb-16 text-center max-w-4xl mx-auto">
<p className="text-sm font-semibold tracking-widest uppercase mb-3 opacity-60" style={{ color: 'var(--deep-earth)' }}>
{getCategorySubtitle(category)}
</p>
<h3 className="text-4xl md:text-5xl font-bold mb-6 tracking-tight" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
{getCategoryTitle(category)} {getCategoryTitle(category)}
</h4> </h3>
{getCategoryDescription(category) && ( {getCategoryDescription(category) && (
<p className="text-gray-600 text-lg leading-relaxed"> <p className="text-lg leading-relaxed opacity-75" style={{ color: 'var(--charcoal-brown)' }}>
{getCategoryDescription(category)} {getCategoryDescription(category)}
</p> </p>
)} )}
</div> </div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6"> {/* Service Cards Grid */}
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
{categoryServices.map((service) => ( {categoryServices.map((service) => (
<article <article
key={service.id} key={service.id}
className="service-card" className="group relative rounded-2xl p-8 transition-all duration-500 hover:shadow-2xl hover:-translate-y-2"
style={{
background: 'var(--soft-cream)',
border: '1px solid transparent'
}}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = 'var(--mocha-taupe)'
e.currentTarget.style.background = 'var(--bone-white)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = 'transparent'
e.currentTarget.style.background = 'var(--soft-cream)'
}}
> >
<div className="mb-4"> {/* Service Header */}
<h5 className="text-xl font-semibold text-gray-900 mb-2"> <div className="mb-6">
<h4 className="text-2xl font-bold mb-3 leading-tight group-hover:opacity-90 transition-opacity" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
{service.name} {service.name}
</h5> </h4>
{service.description && ( {service.description && (
<p className="text-gray-600 text-sm leading-relaxed"> <p className="text-base leading-relaxed opacity-75" style={{ color: 'var(--charcoal-brown)' }}>
{service.description} {service.description}
</p> </p>
)} )}
</div> </div>
<div className="flex items-center justify-between mb-4"> {/* Service Meta */}
<span className="text-gray-500 text-sm"> <div className="flex items-center gap-4 mb-6 pb-6 border-b" style={{ borderColor: 'var(--mocha-taupe)' }}>
{formatDuration(service.duration_minutes)} <div className="flex items-center gap-2">
</span> <svg className="w-5 h-5 opacity-60" fill="none" stroke="currentColor" viewBox="0 0 24 24" style={{ color: 'var(--deep-earth)' }}>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span className="text-sm font-medium opacity-70" style={{ color: 'var(--charcoal-brown)' }}>
{formatDuration(service.duration_minutes)}
</span>
</div>
{service.requires_dual_artist && ( {service.requires_dual_artist && (
<span className="text-xs bg-gray-100 px-2 py-1 rounded-full">Dual Artist</span> <span className="text-xs font-semibold px-3 py-1 rounded-full" style={{ background: 'var(--mocha-taupe)', color: 'var(--bone-white)' }}>
Dual Artist
</span>
)} )}
</div> </div>
{/* Price and CTA */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<span className="text-2xl font-bold text-gray-900"> <div>
{formatCurrency(service.base_price)} <p className="text-xs uppercase tracking-wider mb-1 opacity-50" style={{ color: 'var(--charcoal-brown)' }}>Desde</p>
</span> <p className="text-3xl font-bold" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
<a href="/booking/servicios" className="btn-primary"> {formatCurrency(service.base_price)}
</p>
</div>
<a
href="/booking/servicios"
className="inline-flex items-center justify-center px-6 py-3 text-sm font-medium rounded-lg transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
style={{
background: 'linear-gradient(135deg, var(--deep-earth), var(--charcoal-brown))',
color: 'var(--bone-white)'
}}
>
Reservar Reservar
</a> </a>
</div> </div>
@@ -201,38 +272,55 @@ export default function ServiciosPage() {
</div> </div>
) )
})} })}
</div>
</section>
<section className="testimonials"> {/* Values Section */}
<h3>Lo que Define Anchor 23</h3> <section className="py-24 relative" style={{ background: 'var(--soft-cream)' }}>
<div className="max-w-4xl mx-auto text-center"> <div className="max-w-5xl mx-auto px-8">
<div className="grid md:grid-cols-2 gap-6 text-left"> <h3 className="text-4xl md:text-5xl font-bold mb-16 text-center" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
<div className="space-y-3"> Lo que Define Anchor 23
<div className="flex items-start gap-3"> </h3>
<span className="text-red-500 text-xl"></span> <div className="grid md:grid-cols-2 gap-8">
<span className="text-gray-700">No ofrecemos retoques ni servicios aislados</span> <div className="space-y-6">
</div> {[
<div className="flex items-start gap-3"> 'No ofrecemos retoques ni servicios aislados',
<span className="text-red-500 text-xl"></span> 'No trabajamos con prisas',
<span className="text-gray-700">No trabajamos con prisas</span> 'No explicamos de más'
</div> ].map((text, idx) => (
<div className="flex items-start gap-3"> <div key={idx} className="flex items-start gap-4 p-6 rounded-xl transition-all duration-300 hover:shadow-lg" style={{ background: 'var(--bone-white)' }}>
<span className="text-red-500 text-xl"></span> <div className="flex-shrink-0 w-2 h-2 rounded-full mt-2" style={{ background: 'var(--brick-red)' }}></div>
<span className="text-gray-700">No explicamos de más</span> <p className="text-lg leading-relaxed" style={{ color: 'var(--charcoal-brown)' }}>{text}</p>
</div>
</div> </div>
<div className="space-y-3"> ))}
<div className="flex items-start gap-3">
<span className="text-red-500 text-xl"></span>
<span className="text-gray-700">No negociamos estándares</span>
</div>
<div className="flex items-start gap-3">
<span className="text-red-500 text-xl"></span>
<span className="text-gray-700">Cada experiencia está pensada para durar, sentirse y recordarse</span>
</div>
</div>
</div>
</div> </div>
</section> <div className="space-y-6">
{[
'No negociamos estándares',
'Cada experiencia está pensada para durar, sentirse y recordarse'
].map((text, idx) => (
<div key={idx} className="flex items-start gap-4 p-6 rounded-xl transition-all duration-300 hover:shadow-lg" style={{ background: 'var(--bone-white)' }}>
<div className="flex-shrink-0 w-2 h-2 rounded-full mt-2" style={{ background: 'var(--brick-red)' }}></div>
<p className="text-lg leading-relaxed" style={{ color: 'var(--charcoal-brown)' }}>{text}</p>
</div>
))}
</div>
</div>
</div>
</section>
{/* Final CTA */}
<section className="py-24 text-center" style={{ background: 'var(--bone-white)' }}>
<div className="max-w-3xl mx-auto px-8">
<h3 className="text-4xl md:text-5xl font-bold mb-6" style={{ fontFamily: 'Playfair Display, serif', color: 'var(--charcoal-brown)' }}>
¿Lista para tu experiencia?
</h3>
<p className="text-xl mb-10 opacity-75" style={{ color: 'var(--charcoal-brown)' }}>
Reserva tu cita y descubre lo que significa una atención verdaderamente personalizada.
</p>
<a href="/booking/servicios" className="btn-primary text-base px-12 py-4 inline-block">
Reservar Ahora
</a>
</div> </div>
</section> </section>
</> </>

View File

@@ -1,14 +1,42 @@
import { createClient } from '@supabase/supabase-js' import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL! // Lazy initialization to ensure env vars are available at runtime
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! let supabaseInstance: ReturnType<typeof createClient> | null = null
function getSupabaseClient() {
if (!supabaseInstance) {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
console.log('=== SUPABASE CLIENT INIT ===')
console.log('SUPABASE_URL available:', !!supabaseUrl)
console.log('SUPABASE_ANON_KEY available:', !!supabaseAnonKey)
console.log('SUPABASE_URL value:', supabaseUrl)
console.log('SUPABASE_ANON_KEY preview:', supabaseAnonKey ? supabaseAnonKey.substring(0, 20) + '...' : 'null')
if (!supabaseUrl || !supabaseAnonKey) {
throw new Error(`Missing Supabase environment variables: URL=${!!supabaseUrl}, KEY=${!!supabaseAnonKey}`)
}
supabaseInstance = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true
}
})
console.log('Supabase client initialized successfully')
}
return supabaseInstance
}
// Public Supabase client for client-side operations // Public Supabase client for client-side operations
export const supabase = createClient(supabaseUrl, supabaseAnonKey, { export const supabase = new Proxy({} as ReturnType<typeof createClient>, {
auth: { get(target, prop) {
autoRefreshToken: true, const client = getSupabaseClient()
persistSession: true, return client[prop as keyof typeof client]
detectSessionInUrl: true
} }
}) })