Nuxt3+Supabase Google OAuth登录异常:Chrome未设Cookie仅URL带哈希串
问题描述
使用Supabase和Nuxt3实现Google OAuth登录,代码如下:
<script setup> const user = useSupabaseUser(); const email = ref(''); const errorMsg = ref(''); const { auth } = useSupabaseAuthClient(); const userLogin = async () => { try { const { error } = await auth.signInWithOAuth({ provider: 'google', }); email.value = ''; if (error) throw error; } catch (error) { errorMsg.value = error.message; setTimeout(() => { errorMsg.value = ''; }, 3000); } }; watchEffect(() => { if (user.value) { return navigateTo('/'); } }); </script>
该功能在Safari中运行正常,但Chrome浏览器无法设置Cookie,仅在URL哈希部分返回token(示例URL:localhost:3000/login#access_token=...)。
解决思路
检查Supabase站点与回调URL配置
登录Supabase控制台,进入Authentication > URL Configuration,确保Site URL设置为开发环境地址http://localhost:3000;再进入Authentication > Providers > Google,确认回调URL为http://localhost:3000/api/auth/callback/google(Nuxt Supabase模块默认回调路径)。调整Nuxt Supabase的Cookie配置
在nuxt.config.ts中修改Supabase的Cookie选项,适配Chrome的SameSite规则:export default defineNuxtConfig({ modules: ['@nuxtjs/supabase'], supabase: { url: process.env.SUPABASE_URL, key: process.env.SUPABASE_ANON_KEY, cookieOptions: { sameSite: 'lax', secure: process.env.NODE_ENV === 'production', // 开发环境禁用secure maxAge: 60 * 60 * 24 * 7 } } })检查Chrome的Cookie隐私设置
打开Chrome设置,进入隐私和安全 > Cookie和其他网站数据,确保未启用"阻止所有Cookie",并允许localhost站点的Cookie。若在无痕模式测试,需临时允许第三方Cookie(Chrome默认无痕模式阻止第三方Cookie)。禁用Chrome隐私类插件
暂时关闭广告拦截器、隐私保护类插件(如uBlock Origin、Privacy Badger),这类插件可能拦截Supabase的Cookie写入操作。更新Nuxt Supabase模块
确保@nuxtjs/supabase为最新版本,旧版本可能存在回调处理Bug,无法自动解析URL哈希中的token并完成Cookie设置。
内容的提问来源于stack exchange,提问作者dfd

