supabase.auth.setSession() not working in serverless function

In my SvelteKit app, I need to pass the user's access token & refresh token to an API endpoint, set up an auth session for the user, then fire off some authenticated requests to Supabase. It's not working, though. Details:

First, I fire off a request to an API endpoint like this, passing along the user's access token and refresh token:
const userSession = (await supabase.auth.getSession()).data.session;
const response = await fetch('/api/stripe-checkout-session', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    accessToken: userSession?.access_token ?? '',
    refreshToken: userSession?.refresh_token ?? '',
  })
});


The request handler function for that API endpoint looks like this:
export async function POST(event: RequestEvent): Promise<Response> {
    const { accessToken, refreshToken } = await event.request.json();

    const { data: setSessionData, error: setSessionError } = await supabase.auth.setSession({
        access_token: accessToken,
        refresh_token: refreshToken,
    });

        // 👇 Results in `{ session: null }`
    const { data: getSessionData, error: getSessionError } = await supabase.auth.getSession();
}


When I run console.log(setSessionData), I get this:
{
  session: {
    access_token: 'access-token-goes-here',
    refresh_token: 'refresh-token-goes-here',
    user: { ... },
    token_type: 'bearer',
    expires_in: 2402.638000011444,
    expires_at: 1668490476
  },
  user: {
    id: 'user-id-goes-here',
    aud: 'authenticated',
    role: 'authenticated',
    // ...
  }
}
Was this page helpful?