feat: configurable session initialization to prevent race condition#131
feat: configurable session initialization to prevent race condition#131
Conversation
dc11250 to
9c556eb
Compare
|
@mandarini thanks for opening this, I'm running into this issue since I had to upgrade from Vite 5 => 7 in a SvelteKit project. Important Svelte and SvelteKit are moving really fast right now, since they have experimental support for async Svelte and SvelteKit remote functions. So SvelteKit users that want to keep dependencies up to day have to bump Vite to 7. Is there a workaround I could do to the recommended approach from the docs to sidestep the issue? The best I could come up with (with Claude's help) is: export const handle: Handle = async ({ event, resolve }) => {
// Creates a Supabase client specific to this server request.
// The Supabase client gets the Auth token from the request cookies.
event.locals.supabase = createServerClient(
PUBLIC_SUPABASE_URL,
PUBLIC_SUPABASE_ANON_KEY,
{
cookies: {
getAll: () => event.cookies.getAll(),
// SvelteKit requires cookie `path` to be explicity set
setAll: (cookiesToSet) => {
cookiesToSet.forEach(({ name, value, options }) => {
event.cookies.set(name, value, { ...options, path: '/' });
});
},
},
},
);
// Workaround for supabase/ssr#131: trigger token refresh early
// before resolve() to prevent race condition with Vite 7
await event.locals.supabase.auth.getSession();
// Unlike `supabase.auth.getSession()`, which returns the session _without_
// validating the JWT, this function also calls `getUser()` to validate the
// JWT before returning the session.
event.locals.safeGetSession = async () => {
const {
data: { session },
} = await event.locals.supabase.auth.getSession();
// no session
if (!session) {
return { session: null, user: null };
}
const {
data: { user },
error,
} = await event.locals.supabase.auth.getUser();
// no jwt token
if (error) {
return { session: null, user: null };
}
return { session, user };
};
return resolve(event, {
filterSerializedResponseHeaders(name) {
// forward supabase headers
return name === 'content-range' || name === 'x-supabase-api-version';
},
});
}; |
|
pls help |
|
Can someone add more context for this issue? I've got a branch running vite 7 and async svelte, but I've not run across this issue. |
Having this issue with cookies when using Social Login with callback endpoint like /auth/callback. Working if you're not using any callback endpoint and redirecting to /. |
are you using callback endpoint or root redirect? |
Using a callback endpoint. All auth things are server side |
9c556eb to
120b48c
Compare
|
No actionable comments were generated in the recent review. 🎉 📝 WalkthroughWalkthroughThis PR adds configurable session initialization to the server client via a new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
120b48c to
182343e
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@README.md`:
- Around line 26-86: The TS example in the README is missing a comma after the
cookies object in the createServerClient call and the fenced error block lacks a
language tag; update the snippet near createServerClient so the options object
reads `cookies: { getAll, setAll },` and add a language identifier (e.g.,
```text) to the error fence `Error: Cannot use \`cookies.set(...)\` after the
response has been generated`; after making these edits run Prettier/formatting
on README.md to clear the CI warning.
In `@src/types.ts`:
- Around line 69-76: Prettier is complaining about quote style for the
SessionInitializationMode type; update the string literals in the exported type
SessionInitializationMode in src/types.ts to use the project's preferred quotes
(e.g. change 'auto' | 'manual' to "auto" | "manual") or simply run the project's
Prettier formatter to reformat the file so the union uses the consistent quote
style while keeping the boolean false unchanged.
Summary
Adds a
sessionInitializationconfiguration option tocreateServerClientthat gives users control over automatic session initialization while maintaining backward compatibility.Changes
New
sessionInitializationOptionThree modes available:
'auto'(default) - Automatic initialization on client creation (current behavior)'manual'- Requires explicitawait supabase.auth.initialize()callfalse- No automatic initialization (for read-only contexts)New Methods
supabase.auth.initialize()- Manually trigger initialization (idempotent)supabase.auth.isInitialized()- Check if initialization has completedUsage Examples
Auto mode (default, backward compatible):
Manual mode (explicit control):
Disabled mode (read-only):
Breaking Changes
None - fully backward compatible.
Summary by CodeRabbit
New Features
isInitialized()method to check session initialization statusinitialize()method for manual session initializationDocumentation
Bug Fixes
Tests