session returning null

Hi guys, Question. I have implemented better-auth into my express.js server and I got it working with email and password (sign-up/in) but when it comes to getting a session I get a status code of 200 but a null in return. Basically just followed the docs on installation and under integration of Express. But is there some headers object that I need to catch to get the session or have I missed a step?
app.get("/api/me", async (req, res) => {
try {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
res.json(session);
} catch (e) {
res.status(500).json({ error: "Failed to get session" });
}
});
app.get("/api/me", async (req, res) => {
try {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
res.json(session);
} catch (e) {
res.status(500).json({ error: "Failed to get session" });
}
});
No description
25 Replies
Luv Sharma
Luv Sharma•2mo ago
i also getting the same response null , if you solved the problem , please share with me
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
This has not happened to me earlier in other frameworks but for some reason it happens now. Curious if it has to do with the headers (as we need to pass something special) or missing a frontend.
Luv Sharma
Luv Sharma•2mo ago
did session created on login?
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Yes. I can even see it in the drizzle studio
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
No description
Luv Sharma
Luv Sharma•2mo ago
i am testing in postman , on login with email and password my sessions are not generated and login with google works fine frontend in React backend in Express
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Well that must be in your auth.ts ? Well if I did read it right in the docs our auth.ts should look something like this
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
schema: {
user: user,
session: session,
account: account,
},
}),
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // 1 day
},
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
});
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
schema: {
user: user,
session: session,
account: account,
},
}),
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // 1 day
},
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
});
Luv Sharma
Luv Sharma•2mo ago
this is my controller to retrieve session and this is my auth.ts
No description
No description
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Wait your using auth.api.getSession()but shouldn't you be using the auth-client.ts file instead?
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
/** The base URL of the server (optional if you're using the same domain) */
baseURL: "http://localhost:3000"
})
And then follow that with
export const { signIn, signUp, useSession } = createAuthClient()
export const { signIn, signUp, useSession } = createAuthClient()
So you would do something like authClient.useSession()
Luv Sharma
Luv Sharma•2mo ago
this file auth-client.ts i am using this in my frontend did i have to use this file in backend
No description
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
No description
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Ok but your function getCurrentUser()where is that from? Your backend or frontend?
Luv Sharma
Luv Sharma•2mo ago
in backend
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Aaa ok. I'm stupid 🤣 I have no idea man. Seems to be a problem that I cannot solve. Waiting for help
Luv Sharma
Luv Sharma•2mo ago
nobody has made a yt video on this configuration 😭 ok bro , thanks for your time
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
@Luv Sharma I fixed it. I can explain when your available. I had some help from one of the admins. To get your session on the server side or from postman you need to pass in headers a cookie named better-auth.session_token=YOUR_TOKEN_GOES_HERE and you will get your user session from Postman/httipie or simular programs
Luv Sharma
Luv Sharma•2mo ago
the problem is sessions are not created on my backend when i am using this ( Img 1 ) but , when i directly signin on my frontend with this logic ( Img 2 ) , session are created , here's what i learn : When we use auth.ts ( on backend ) file to signIn user , the sessions are not created , but when we use auth-client.ts ( on frontend ) file to signIn user directly without backend , the session are created : that is the same problem i faced in nextjs also , moral of the story : auth.ts does not created sessions here's the video proof :
No description
No description
No description
Luv Sharma
Luv Sharma•2mo ago
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
1. We want to fix the backend before we do anything else in the frontend. 2. After we get the backend working we can make it work with the frontend. Let's together try to sort this problem then. Can you make an API endpoint in your backend that hits the following endpoint app.all("/api/auth/*splat", toNodeHandler(auth)); After you have added the endpoint in your backend then hit the following endpoint: /api/me and don't forget to include the better-auth.session_token=YOUR_TOKEN_GOES_HERE in your headers
Luv Sharma
Luv Sharma•2mo ago
did your sessions are created on backend , can u show me your code ?
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Yes my session are created in Node+express.js
Luv Sharma
Luv Sharma•2mo ago
can u show me the code bro? i have also done that , but still not sessions are created
Jacob | idohtml
Jacob | idohtmlOP•2mo ago
Which part do you want to see that I have not shown you? Here is the index.ts file
import "dotenv/config";
import express from "express";
import cors from "cors";
import { toNodeHandler, fromNodeHeaders } from "better-auth/node";
import { auth } from "@/lib/auth.js";

const app = express();

// Better Auth routes
app.all("/api/auth/*splat", toNodeHandler(auth));

// Cors
app.use(
cors({
origin: true,
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
}),
);

// Body parser
app.use(express.json());

app.get("/", (req, res) => {
res.send("Business Management API");
});

// Exempel: GET request for user session
app.get("/api/me", async (req, res) => {
try {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
res.json(session);
} catch (e) {
res.status(500).json({ error: "Failed to get session" });
}
});

// Health check
app.get("/health", (_req, res) => {
res.json({ ok: true, uptime: process.uptime() });
});

const PORT = Number(process.env.PORT) || 3000;
app.listen(PORT, () => {
console.log(`API running on http://localhost:${PORT}`);
});
import "dotenv/config";
import express from "express";
import cors from "cors";
import { toNodeHandler, fromNodeHeaders } from "better-auth/node";
import { auth } from "@/lib/auth.js";

const app = express();

// Better Auth routes
app.all("/api/auth/*splat", toNodeHandler(auth));

// Cors
app.use(
cors({
origin: true,
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
}),
);

// Body parser
app.use(express.json());

app.get("/", (req, res) => {
res.send("Business Management API");
});

// Exempel: GET request for user session
app.get("/api/me", async (req, res) => {
try {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
res.json(session);
} catch (e) {
res.status(500).json({ error: "Failed to get session" });
}
});

// Health check
app.get("/health", (_req, res) => {
res.json({ ok: true, uptime: process.uptime() });
});

const PORT = Number(process.env.PORT) || 3000;
app.listen(PORT, () => {
console.log(`API running on http://localhost:${PORT}`);
});
Here is my auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/db/index.js"; // your drizzle instance
import { account, session, user } from "@/db/schema.js";

export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
schema: {
user: user,
session: session,
account: account,
},
}),
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
cookieCache: {
enabled: true,
maxAge: 5 * 60,
},
},
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
});
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/db/index.js"; // your drizzle instance
import { account, session, user } from "@/db/schema.js";

export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg", // or "mysql", "sqlite"
schema: {
user: user,
session: session,
account: account,
},
}),
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
cookieCache: {
enabled: true,
maxAge: 5 * 60,
},
},
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
});
Luv Sharma
Luv Sharma•3w ago
Hi , bro is Your express + better auth working good ?
Vishnu
Vishnu•8h ago
Hi @Luv Sharma is it working for you now ?

Did you find this page helpful?