Files
shorturl-analytics/lib/supabase.ts

100 lines
3.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createClient } from '@supabase/supabase-js';
// 从环境变量获取Supabase配置
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL || '';
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY || '';
console.log('Supabase Configuration Check:', {
urlDefined: !!supabaseUrl,
keyDefined: !!supabaseAnonKey,
url: supabaseUrl,
// 打印部分key以便调试
keyPrefix: supabaseAnonKey ? supabaseAnonKey.substring(0, 20) + '...' : 'undefined',
keyLength: supabaseAnonKey ? supabaseAnonKey.length : 0
});
if (!supabaseUrl || !supabaseAnonKey) {
console.error('Supabase URL and Anon Key are required');
}
// 尝试解码JWT token并打印解码内容
try {
if (supabaseAnonKey) {
const parts = supabaseAnonKey.split('.');
if (parts.length === 3) {
const payload = parts[1];
const decoded = atob(payload);
console.log('JWT Payload:', decoded);
} else {
console.error('Invalid JWT format, expected 3 parts but got:', parts.length);
}
}
} catch (error) {
console.error('JWT解码失败:', error);
}
// 创建自定义cookie处理逻辑
const customStorage = {
getItem: (key: string): string | null => {
if (typeof document === 'undefined') return null;
const cookie = document.cookie
.split(';')
.find((c) => c.trim().startsWith(`${key}=`));
return cookie ? cookie.split('=')[1] : null;
},
setItem: (key: string, value: string): void => {
if (typeof document === 'undefined') return;
// 获取当前主机和端口处理localhost上的不同端口情况
const host = typeof window !== 'undefined' ? window.location.hostname : '';
// 设置cookie对localhost使用通用domain
document.cookie = `${key}=${value}; path=/; max-age=${60 * 60 * 24 * 7}; samesite=lax; domain=${host}`;
console.log(`Cookie ${key} 已设置domain=${host}`);
},
removeItem: (key: string): void => {
if (typeof document === 'undefined') return;
// 获取当前主机和端口处理localhost上的不同端口情况
const host = typeof window !== 'undefined' ? window.location.hostname : '';
// 删除cookie对localhost使用通用domain
document.cookie = `${key}=; path=/; max-age=0; samesite=lax; domain=${host}`;
console.log(`Cookie ${key} 已移除`);
},
};
// 创建Supabase客户端
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
persistSession: true,
autoRefreshToken: true,
detectSessionInUrl: true,
storageKey: 'sb-auth-token',
storage: customStorage
}
});
// 测试Supabase连接
supabase.auth.onAuthStateChange((event, session) => {
console.log(`Supabase auth event: ${event}`, session ? 'Session exists' : 'No session');
if (session) {
console.log('Current user:', session.user.email);
}
});
// 尝试执行健康检查
async function checkSupabaseHealth() {
try {
const { data, error } = await supabase.from('_health').select('*').limit(1);
console.log('Supabase health check:', error ? `Error: ${error.message}` : 'Success', data);
} catch (error) {
console.error('Supabase health check error:', error);
}
}
checkSupabaseHealth();
export default supabase;