无法在SvelteKit中使用Pocketbase OAuth授权求助
在SvelteKit中使用Pocketbase OAuth时解决"EventSource is not defined"错误
在SvelteKit项目中尝试通过Pocketbase的authWithOAuth2实现Google登录时,遇到ReferenceError: EventSource is not defined错误,核心原因是EventSource是浏览器专属API,代码在SvelteKit服务端环境执行时无法访问该API。以下是具体解决方案:
解决方案1:禁用Pocketbase的自动实时连接
Pocketbase默认会自动连接实时服务,而该功能依赖浏览器的EventSource API。初始化Pocketbase实例时关闭自动实时连接即可避免报错:
// hooks.server.ts 中初始化Pocketbase import PocketBase from 'pocketbase'; export async function handle({ event, resolve }) { event.locals.pb = new PocketBase('https://your-pocketbase-instance.com'); // 禁用自动连接实时服务,规避服务端环境的EventSource缺失问题 event.locals.pb.autoJoinRealtime = false; // 可选:加载已有用户会话 event.locals.pb.authStore.loadFromCookie(event.request.headers.get('cookie') || ''); try { if (event.locals.pb.authStore.isValid) { await event.locals.pb.collection('users').authRefresh(); } } catch (_) { event.locals.pb.authStore.clear(); } const response = await resolve(event); // 可选:更新会话cookie response.headers.set('set-cookie', event.locals.pb.authStore.exportToCookie({ secure: true })); return response; }
解决方案2:将OAuth登录逻辑放在客户端执行
OAuth登录需要跳转到第三方授权页面,本质是客户端行为,直接在Svelte组件中执行登录逻辑更合理:
<!-- +page.svelte --> <script> import PocketBase from 'pocketbase'; import { page } from '$app/stores'; const pb = new PocketBase('https://your-pocketbase-instance.com'); // 从页面数据加载已有会话 pb.authStore.loadFromCookie($page.data.cookie || ''); const loginWithGoogle = async () => { try { await pb.collection('users').authWithOAuth2({ provider: 'google' }); // 登录成功后跳转或更新页面状态 window.location.href = '/'; } catch (err) { console.error('登录失败:', err); } }; </script> <button on:click={loginWithGoogle}>使用Google登录</button>
解决方案3:服务端Action中手动处理OAuth跳转
如果需要在服务端Action中处理登录(比如管理会话Cookie),可通过urlOnly: true获取授权URL,让客户端自行跳转:
// +page.server.ts import type { Actions } from './$types'; export const actions: Actions = { loginWithGoogle: async ({ locals }) => { // 临时禁用实时连接 locals.pb.autoJoinRealtime = false; // 获取Google授权URL,服务端不自动跳转(无法操作浏览器) const authData = await locals.pb.collection('users').authWithOAuth2({ provider: 'google', urlOnly: true, redirectUrl: 'https://your-app.com/auth/callback' // 配置的回调地址 }); return { redirect: authData.authUrl }; } };
客户端组件调用Action并跳转:
<!-- +page.svelte --> <script> import { enhance } from '$app/forms'; </script> <form method="POST" action="?/loginWithGoogle" use:enhance={({ result }) => { if (result.type === 'success') { window.location.href = result.data.redirect; } }}> <button type="submit">使用Google登录</button> </form>
核心原因说明
EventSource是浏览器用于Server-Sent Events的专属API,Node.js环境(SvelteKit服务端)中不存在该对象。Pocketbase默认会自动连接实时服务,当代码在服务端执行时就会触发这个错误。通过禁用自动实时连接,或者将OAuth逻辑移到客户端执行,就能彻底解决问题。
内容的提问来源于stack exchange,提问作者Kraktoos
相关产品推荐
相关产品推荐

