I'm building a full-stack application using Bun, Express, Node.js, MongoDB, and Better Auth for authentication. The app works perfectly on localhost, but after deploying to Vercel, cookies are not being saved in the frontend after user sign-in, causing authentication to fail on page refresh.
- Cookies are not being saved in the frontend after user sign-in
- Frontend is not sending cookies to backend via request headers in subsequent API calls
Tech Stack:
- Backend: Bun + Express + Better Auth + MongoDB
- Frontend: React.js + Tailwind CSS + Better Auth Client
- Deployment: Vercel
- Auth Provider: GitHub OAuth
Current Configuration:
authInstance = betterAuth({
advanced: {
cookies: {
session_token: {
name: "session_token",
attributes: {
sameSite: "None",
domain: "ai-test-case-iprf.vercel.app",
path: "/",
secure: true,
httpOnly: false,
},
},
},
},
database: mongodbAdapter(db),
baseURL: process.env.BETTER_AUTH_URL,
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
},
},
trustedOrigins: [
process.env.FRONTEND_URL,
process.env.BETTER_AUTH_URL,
],
});
Environment Variables:
BETTER_AUTH_URL:https://my-backend-is-differ.vercel.appFRONTEND_URL:https://ai-test-case-iprf.vercel.app
Problem:
- Localhost: Authentication works perfectly, cookies are set and persist
- Production (Vercel):
- Sign-in API call succeeds
- User gets redirected properly
- BUT cookies are not saved in browser
- Page refresh loses authentication state
What I've Tried:
Cookie Configuration:
- Set
sameSite: "None"andsecure: truefor cross-origin - Tried
httpOnly: falseto make cookies accessible - Set explicit domain matching my Vercel deployment
- Set
CORS Configuration:
- Added frontend URL to
trustedOrigins
- Added frontend URL to
Multiple Deployment Attempts:
- Redeployed several times with different configurations
- Verified environment variables are set correctly
Browser Developer Tools:
Network Tab:
- Sign-in request:
200 OKbut noSet-Cookieheaders visible - Subsequent API calls: No
Cookieheader in request
Application Tab:
- No session cookies appear after successful sign-in
- Cookie storage remains empty
Console:
- No CORS errors
- No explicit cookie-related errors
Questions:
- Are there specific Vercel deployment configurations needed for Better Auth cookies?
- Should I avoid setting an explicit
domainfor.vercel.appdeployments? - Do I need additional frontend configuration to accept cross-origin cookies?
- Is there a Better Auth + Vercel specific setup I'm missing?