Supabase Google Auth: No Cookie Set After Sign-In

I’m experiencing an issue with my Vercel app using Supabase for Google authentication. After a user signs in, no cookie is being set, which prevents the app from detecting if a user is already signed in.

Current Setup

  1. I’m using Supabase for authentication in my Vercel app.
  2. Google auth is implemented for sign-in.

The Issue

After successful authentication, no cookie is set. This causes the following problems:

  1. The app can’t detect if a user is already signed in.
  2. Each page load requires re-authentication.

Relevant Code

Here’s the sign-in handler:

const { createClient } = require('@supabase/supabase-js');

module.exports = async (req, res) => {
  const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY);
  
  const { data, error } = await supabase.auth.signInWithOAuth({
    provider: 'google',
    options: {
      redirectTo: `http://localhost:3000/api/auth_callback`,
    },
  });

  console.log("here come sdata:", data);

  if (error) {
    return res.status(401).json({ error: error.message });
  }

  if (data.url) {
    res.redirect(data.url);
  } else {
    res.status(500).json({ error: 'No URL returned from Supabase' });
  }
};

And here’s the auth check:

const { createClient } = require('@supabase/supabase-js');

module.exports = async (req, res) => {
  console.log('Auth check endpoint hit');
  console.log('Cookies:', req.headers.cookie);
  
  const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY);

  // Extract the session token from the cookie
  const sessionToken = req.headers.cookie?.split(';')
    .find(c => c.trim().startsWith('sb-access-token='))
    ?.split('=')[1];
  console.log('Session token:', sessionToken);
  if (!sessionToken) {
    console.log('No session token found in cookies');
    return res.json({ authenticated: false });
  }

  try {
    const { data, error } = await supabase.auth.getUser(sessionToken);

    if (error) throw error;

    if (data.user) {
      console.log('User authenticated');
      res.json({ authenticated: true });
    } else {
      console.log('User not authenticated');
      res.json({ authenticated: false });
    }
  } catch (error) {
    console.error('Error checking authentication:', error);
    res.status(500).json({ error: error.message });
  }
};

Expected Behavior

After successful authentication, a cookie should be set to maintain the user’s session.

Questions

  1. Is there a step I’m missing in the authentication flow?
  2. Are there any specific configurations needed for Vercel deployments to allow cookie setting?
  3. Could this be related to CORS or other security settings?

Any insights or suggestions would be greatly appreciated. Thank you!

Hello,
It has some thing with the cors, probably.,

Im facing same issue with another oauth provider.,
did you find any solution?

Hi, @yachty66! Thanks for your patience and for providing detailed information about your issue. :pray: I know it’s been a while since we last heard from you, I was wondering if you managed to find a solution?

I’ll try and answer as much as I can now, anyway.

  1. Is there a step I’m missing in the authentication flow?

Yes, there seems to be a missing step in your authentication flow. The current setup doesn’t explicitly set a cookie after successful authentication. When using Supabase with Next.js, you typically need to set the session cookie on the client side after a successful sign-in.

Cross-posting some templates which might be helpful to look at: Supabase Auth Examples & Templates | Vercel – Vercel

  1. Are there any specific configurations needed for Vercel deployments to allow cookie setting?

Vercel doesn’t require any specific configurations to allow cookie setting. However, you need to ensure that you’re setting the cookie correctly and that it’s being sent with subsequent requests .

  1. Could this be related to CORS or other security settings?

While CORS could potentially cause issues, it’s more likely that the problem is related to how the authentication flow is implemented and how the session is being managed.

Some ideas of what you could try to resolve your authentication issue:

  1. Update your sign-in handler to use the createServerSupabaseClient from @supabase/auth-helpers-nextjs instead of creating a new Supabase client.
  2. Implement a callback handler (/api/auth/callback) to exchange the code for a session and set the session cookie.
  3. On the client side, use the createBrowserSupabaseClient from @supabase/auth-helpers-nextjs to manage the session. This client automatically handles refreshing the session and updating the cookie .
  4. In your auth check function, use the getSession method from the Supabase client instead of manually parsing cookies. This ensures you’re using the most up-to-date session information .
  5. Make sure you’re using the latest version of @supabase/auth-helpers-nextjs and @supabase/supabase-js

Thanks again for your patience with us!

Hi, @kumaran1980!

I’m unsure of your project set-up, but I wrote a response above that might be helpful. Let us know what you end up trying out!