better-auth Session Not Recognized After Manual Creation in Telegram Callback

Telegram successfully authenticates, and my callback verifies the data. However, I'm manually creating the session record in the DB and setting the session cookie afterwards. Below how I'm doing it in my /api/auth/callback/telegram.ts. After this manual setup and redirecting to a protected route, my middleware check await auth.api.getSession(...) fails to recognize the session, causing a redirect back to /signin. My Question: Is manually inserting into the session table and setting the better-auth.session_token cookie like this the correct approach for integrating a custom callback (like Telegram's data-auth-url) with better-auth?
// 1. Manually Create Session Record in DB
const sessionToken = crypto.randomBytes(32).toString("hex");
await userDb.insert(session).values({
id: crypto.randomUUID(),
userId: userId, // Gotten from finding/creating user earlier
expiresAt: sessionExpiresAt,
token: sessionToken, // Store the generated token
createdAt: nowForSession,
updatedAt: nowForSession,
ipAddress: clientAddress,
userAgent: userAgent,
}).execute();

// 2. Manually Set Cookie using Astro's helper
cookies.set("better-auth.session_token", sessionToken, {
path: "/",
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: "lax",
maxAge: SESSION_MAX_AGE // e.g., 30 days
});
// 1. Manually Create Session Record in DB
const sessionToken = crypto.randomBytes(32).toString("hex");
await userDb.insert(session).values({
id: crypto.randomUUID(),
userId: userId, // Gotten from finding/creating user earlier
expiresAt: sessionExpiresAt,
token: sessionToken, // Store the generated token
createdAt: nowForSession,
updatedAt: nowForSession,
ipAddress: clientAddress,
userAgent: userAgent,
}).execute();

// 2. Manually Set Cookie using Astro's helper
cookies.set("better-auth.session_token", sessionToken, {
path: "/",
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: "lax",
maxAge: SESSION_MAX_AGE // e.g., 30 days
});
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?