BA
Better Auth•22h ago
Vishnu

🆘 Need help with Better Auth + Express + MongoDB (Session always null)

Hey everyone 👋 I'm using Better Auth with Express, TypeScript, and MongoDB. I've set up authentication as per the docs — login works fine and I can see the session being created in my database. However, when I call auth.api.getSession, it always returns null. auth.ts import { betterAuth } from "better-auth"; import { MongoClient } from "mongodb"; import { databaseConfig } from "../config/db.config.js"; import { mongodbAdapter } from "better-auth/adapters/mongodb"; const mongoClient = new MongoClient(databaseConfig.uri); const db = mongoClient.db(); export const auth = betterAuth({ user: { additionalFields: { isActive: { type: "boolean", defaultValue: false }, firstName: { type: "string", required: true }, lastName: { type: "string", required: true }, mobileNumber: { type: "string", required: true }, role: { type: "string", required: true, references: { model: "roles", field: "_id" }, }, team: { type: "string", required: false, references: { model: "teams", field: "_id" }, }, }, }, emailAndPassword: { enabled: true }, advanced: { useSecureCookies: false, defaultCookieAttributes: { httpOnly: true, sameSite: "None", secure: false, maxAge: 1000000, }, }, session: { expiresIn: 60 * 60 * 24 * 7, cookieCache: { enabled: true, maxAge: 5 * 60 }, }, database: mongodbAdapter(db, { client: mongoClient }), }); 🧠 What’s happening /auth/login works fine. I get this response also sessioncreated : { "message": "Login successful", "data": { "redirect": true, "token": "RY7qleTD0SwUNggG9bBzp17hfMblIAs7", "url": "https://google.com", "user": { "id": "68f5ef166e37cd53cc1724be", "email": "john@gmail.com", "name": "John Doe", "emailVerified": false, "createdAt": "2025-10-20T08:13:10.192Z", "updatedAt": "2025-10-20T08:13:10.192Z" } } }
10 Replies
Vishnu
VishnuOP•22h ago
/login route service
No description
Vishnu
VishnuOP•22h ago
/ login route controller
No description
Vishnu
VishnuOP•22h ago
getSession call always returns null
No description
Vishnu
VishnuOP•17h ago
@Better Auth any input on this ?
Better Auth
Better Auth•17h ago
Error: Bad request: The server couldn't process your request. Please check your input. — Better Auth is powered by https://clarm.com
Clarm
Automate customer support with AI for developer, finance, and technical teams
Vishnu
VishnuOP•17h ago
@Better Auth any input on this ?
Better Auth
Better Auth•17h ago
Error: Bad request: The server couldn't process your request. Please check your input. — Better Auth is powered by https://clarm.com
Clarm
Automate customer support with AI for developer, finance, and technical teams
Hexi
Hexi•15h ago
Are you vibe coding or something?? Follow the docs...
sudoramz
sudoramz•15h ago
const data = await auth.api.signInEmail({
body: {
email: "john.doe@example.com", // required
password: "password1234", // required
rememberMe: true,
callbackURL: "https://example.com/callback",
},
// This endpoint requires session cookies.
headers: await headers(),
});
const data = await auth.api.signInEmail({
body: {
email: "john.doe@example.com", // required
password: "password1234", // required
rememberMe: true,
callbackURL: "https://example.com/callback",
},
// This endpoint requires session cookies.
headers: await headers(),
});
Try adding headers on your login call.
Vishnu
VishnuOP•6h ago
Thanks for the response! I tried passing the headers, but it didn’t work for me. although i did find a way to make it work I tried using the default Better Auth endpoint /api/auth/sign-in/email, and I noticed that it sets two cookies automatically: better-auth.session_token and (optionally) better-auth.session_data. However, when I created a custom login endpoint and used the signInEmail method, it didn’t set any cookies. I’m not entirely sure if that’s the default behavior or if I missed something. To fix this, I manually set the cookies myself. While checking the implementation, I also noticed that Better Auth uses signed cookies in the format {sessionToken}.{signature}. So, I tried signing the token in the same way Better Auth expects and voila, it worked! Here’s the code I used to sign the session token: import crypto from 'crypto' export function signSessionToken(sessionToken: string, secret: string) { const hmac = crypto.createHmac("sha256", secret); hmac.update(sessionToken); const signature = hmac.digest("base64"); return ${sessionToken}.${signature}; } I found another way to handle this. In the signInEmail call, I added returnHeaders: true, which returned the response headers in the data variable. From there, I extracted the cookies using the getSetCookies method and manually set them in the response with res.setHeader('Set-Cookie', setCookies). This successfully stored the cookies on the client. I’m not sure if there’s a better way to handle this, but I’m definitely open to suggestions.

Did you find this page helpful?