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
- I’m using Supabase for authentication in my Vercel app.
- Google auth is implemented for sign-in.
The Issue
After successful authentication, no cookie is set. This causes the following problems:
- The app can’t detect if a user is already signed in.
- 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
- Is there a step I’m missing in the authentication flow?
- Are there any specific configurations needed for Vercel deployments to allow cookie setting?
- Could this be related to CORS or other security settings?
Any insights or suggestions would be greatly appreciated. Thank you!