NextJS handler not setting the cookie in production

Hey 👋 , My handler isn't setting the cookie on the client browser in production only. I'm using next 15.3 and better auth ^1.2.7 Thanks for your help guys here is my auth config§
export const auth = betterAuth({
emailAndPassword: {
enabled: false,
},
database: prismaAdapter(prisma, {
provider: "postgresql",
}),
plugins: [
magicLink({
sendMagicLink: async ({ email, url }) => {
await resend.emails.send({
from: "LGC <contact@lgc-supervision.site>",
to: email,
subject: "Lien de connexion à LGC Supervision",
react: await EmailTemplate({ url }),
});
},
}),
nextCookies(),
],
callbacks: {
async session({
session,
user,
}: {
session: CustomSession;
user: { id: string };
}) {
const fullUser = await prisma.user.findUnique({
where: { id: user.id },
include: { company: true },
}) as User & { company: Company | null };

session.user.name = fullUser.name;
session.user.email = fullUser.email;
session.user.role = fullUser.role;

if (fullUser.company) {
session.user.company = {
name: fullUser.company.name,
color: fullUser.company.color,
};
}

return session;
},
},
});
export const auth = betterAuth({
emailAndPassword: {
enabled: false,
},
database: prismaAdapter(prisma, {
provider: "postgresql",
}),
plugins: [
magicLink({
sendMagicLink: async ({ email, url }) => {
await resend.emails.send({
from: "LGC <contact@lgc-supervision.site>",
to: email,
subject: "Lien de connexion à LGC Supervision",
react: await EmailTemplate({ url }),
});
},
}),
nextCookies(),
],
callbacks: {
async session({
session,
user,
}: {
session: CustomSession;
user: { id: string };
}) {
const fullUser = await prisma.user.findUnique({
where: { id: user.id },
include: { company: true },
}) as User & { company: Company | null };

session.user.name = fullUser.name;
session.user.email = fullUser.email;
session.user.role = fullUser.role;

if (fullUser.company) {
session.user.company = {
name: fullUser.company.name,
color: fullUser.company.color,
};
}

return session;
},
},
});
my route handler
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { POST, GET } = toNextJsHandler(auth);
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { POST, GET } = toNextJsHandler(auth);
13 Replies
Ping
Ping•3mo ago
Which method are you calling which you expect to set cookie in production? Can you show us the code for it?
k_a_i_y_o
k_a_i_y_oOP•3mo ago
Hello, thank you for your reply. Sorry, I don't know which file you want. Could you please tell me which file you need?
jjjjjjjjj
jjjjjjjjj•3mo ago
Same error, the exact same code as the dev environment but the cookie isn't set
Eren©
Eren©•2mo ago
@k_a_i_y_o ever found a solution to this mate? struggling with the same thing although I was using cross-origin auth so had to first correct my config to support sameSite and strict. Here's my config:
export const auth = betterAuth({
trustedOrigins: [config.CLIENT_ORIGIN],
advanced: {
useSecureCookies: config.NODE_ENV === 'production',
defaultCookieAttributes: {
secure: config.NODE_ENV === 'production',
partitioned: config.NODE_ENV === 'production',
sameSite: config.NODE_ENV === 'production' ? 'None' : 'Lax'
}
},
emailAndPassword: {
enabled: true
},
..................
}
export const auth = betterAuth({
trustedOrigins: [config.CLIENT_ORIGIN],
advanced: {
useSecureCookies: config.NODE_ENV === 'production',
defaultCookieAttributes: {
secure: config.NODE_ENV === 'production',
partitioned: config.NODE_ENV === 'production',
sameSite: config.NODE_ENV === 'production' ? 'None' : 'Lax'
}
},
emailAndPassword: {
enabled: true
},
..................
}
It's the login command
Ping
Ping•2mo ago
SignInEmail?
Eren©
Eren©•2mo ago
Yes
Ping
Ping•2mo ago
Are you on nextjs?
Eren©
Eren©•5w ago
Yes, nextjs for frontend and fastify for backend Using the auth client in a client component Everything works as expected on localhost but on production, the calls occur and I'm redirected to dashboard as well but then sent back to login page due to lack of cookies because I have a check at dashboard The cookies are never set @Ping any updates mate?
Abdifitah Abdulkadir
@Eren© Hello, please I am not expert on better auth, amd I am currently exploring it . But also, I am not sure If I understood your question well regard better auth. But let me point two main cases that I think it is important : 1. If you are using server side authentication for better auth, like server actions in the nextjs or route handlers, then you need to set cookies for you self manually or -most recommended way, to use nextCookies() plugin in your plugin auth.ts file. that way, better auth will set cookie for you when you signIn and signUp automatically. 2. And otherwise, if you are using cient side authentication like auth-client.ts file then simply , it should automatically set cookies for you. Big Disclaimer , I did not test it in production, and that is my understanding so far.
Eren©
Eren©•5w ago
your understanding is correct, I'm using client side authentication and the cookies must be set automatically. Initially, I was using the example provided config from better auth which had no mention of secure cookies, same site attribute or partitioned attribute. But that did not matter as I was just using it on dev environment. Once I deployed it, nothing happened after logging in and when I checked console. It stated that for security reasons, the browser has declined the cookies to be set from better auth. So, I checked and found that better auth requires NODE_ENV environment set to production for it to automatically handle secure cookies attributes in production. I did that but still got the same message and then I explicitly configured the secure cookies based on my environment:
advanced: {
useSecureCookies: config.NODE_ENV === 'production',
defaultCookieAttributes: {
secure: config.NODE_ENV === 'production',
partitioned: config.NODE_ENV === 'production',
sameSite: config.NODE_ENV === 'production' ? 'None' : 'Lax'
}
},
advanced: {
useSecureCookies: config.NODE_ENV === 'production',
defaultCookieAttributes: {
secure: config.NODE_ENV === 'production',
partitioned: config.NODE_ENV === 'production',
sameSite: config.NODE_ENV === 'production' ? 'None' : 'Lax'
}
},
After this, the browser stopped giving that error in console and everything seemed to be working fine but I was still getting redirected to login page from my dashboard (because of the auth check). I checked the browser storage and found that despite successful login, no cookies have been set. But same thing in development environment, the cookies are set and everything works flawlessly. I'm not sure what I'm doing wrong and there doesn't seem to be much content about this issue on forums either, that's why I reached out here. Hope this explanation helped you understand better
Abdifitah Abdulkadir
Yeah, really, that is correct, @Eren© , what about if you switch to Server action form type authentication --server side authentication to see if that solves your issue. and then later you can explore what went wrong and why or perhaps if that is Bug from better auth its self. and with help of nextCookies() plugin, I think you should test that apprach and see if it works on your project.
Eren©
Eren©•5w ago
I've moved on from fixing this for now and working on rest of the features. Once I come back to this, that'll my last resort if I don't get any solution for this. There are some posts regarding the same issue with no viable solution so I thought it's better to see if it's a bug or I am doing something wrong
Abdifitah Abdulkadir
yeah, I hope that wil solve your issue, and otherwise if that also does not work then means non one can use better auth in production. I hope again it will work.😆

Did you find this page helpful?