Cookies not saved in production

I have a node/express backend and a vite react frontend. They are on different urls: Backend: http://my-backend.vercel.app/ auth.ts looks like this:
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql",
}),
emailAndPassword: {
enabled: true
},
trustedOrigins: ["http://localhost:5173", "https://my-frontend.vercel.app"],
cookies: {
sameSite: "lax",
path: "/",
secure: process.env.NODE_ENV === "production",
httpOnly: true
}
});
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql",
}),
emailAndPassword: {
enabled: true
},
trustedOrigins: ["http://localhost:5173", "https://my-frontend.vercel.app"],
cookies: {
sameSite: "lax",
path: "/",
secure: process.env.NODE_ENV === "production",
httpOnly: true
}
});
Frontend: https://my-frontend.vercel.app
import { createAuthClient } from "better-auth/react"

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:3000";

export const authClient = createAuthClient({
baseURL: API_BASE_URL,
})
import { createAuthClient } from "better-auth/react"

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:3000";

export const authClient = createAuthClient({
baseURL: API_BASE_URL,
})
On local it works fine. But on production, it calls the api, but the session cookie doesn't get saved. Can you please help with what's wrong here?
3 Replies
Manish
ManishOP2w ago
I noticed that when I login from frontend, it does set the cookie, but cookie domain is the backend url. That's why when I refresh the page, it just vanishes. How do I resolve this?
Felix
Felix2w ago
Are your backend and frontend using the same domain? Then configure cross-domain cookies https://www.better-auth.com/docs/concepts/cookies#cross-subdomain-cookies
Cookies | Better Auth
Learn how cookies are used in Better Auth.
Manish
ManishOP2w ago
The problem got resolved by moving from vercel.app to my own custiom domain. On vercel.app, vercel was creating some problem with setting the cookie as per our specs.

Did you find this page helpful?