Md Faizan
Md Faizan

Reputation: 1

Why i am getting null user session in my client side Teck Stack: Backend- Hono with Node, Frontend- Next js

When i am trying to get user session from my hono+node server. Auth library is better-auth. My end point is "/user/session" but when i am trying getting session i get null but in my middleware i am able get proper session information

/src/index.ts

const app = new Hono();
const port = Number(process.env.PORT) || 8080;

// Middleware
app.use(logger());
// Better auth Middleware, docs: https://www.better-auth.com/docs/integrations/hono#middleware
app.use("*", addSession);
app.use("*", errorHandler);
app.use("*", configCors);

// Database
db();

// Auth Route
app.on(["POST", "GET"], "/api/auth/**", (c) => {
  return auth.handler(c.req.raw);
});

// Main Route
app.get("/", (c) => c.text("Welcome to the Telegram Bot API!"));


// Routes
app.route("/api", routes);
// user session route
app.route("/user", sessionRoute);

// Telegram Bot
initBot();

serve({
  fetch: app.fetch,
  port,
});
middleware/session.middleware.js

const addSession = async (c: Context, next: Next) => {
  const session = await auth.api.getSession({ headers: c.req.raw.headers });

  console.log("Middleware - Session: ", session)

  if (!session) {
    c.set("user", null);
    c.set("session", null);
    return next();
  }

  c.set("user", session.user);
  c.set("session", session.session);

  return next();
};

export default addSession;

routes/session.route.js

const sessionRoute = new Hono<AuthSession>();

sessionRoute.get("/session", async (c) => {
  const session = c.get("session");
  const user = c.get("user");

  console.log("Route - Session: ", session, "User: ", user);

  if (!user) return c.body(null, 401);

  return c.json(
    {
      session,
      user,
    },
    200
  );
});

export default sessionRoute
auth.ts

const db = client.db();

export const auth = betterAuth({
  database: mongodbAdapter(db),
  trustedOrigins: [CLIENT_DOMAIN],
  socialProviders: {
    google: {
      clientId: GOOGLE_CLIENT_ID,
      clientSecret: GOOGLE_CLIENT_SECRET,
    },
  },
  advanced: {
    defaultCookieAttributes: {
      sameSite: "none",
      secure: true,
    },
  },
});

Logs

New mongoose connection is established
<-- GET /user/session
Middleware - Session:  null
Route - Session:  null User:  null
--> GET /user/session 401 44ms
<-- GET /api/auth/get-session
Middleware - Session:  null
--> GET /api/auth/get-session 200 38ms
<-- GET /api/auth/get-session
Middleware - Session:  {
  session: {
    id: '6795ca509caad08b2cc0c20e',
    expiresAt: 2025-02-02T05:38:24.038Z,
    token: 'Iyu11ZgdrGLhctuZN1uuc7Rpfs7yso2v',
    createdAt: 2025-01-26T05:38:24.038Z,
    updatedAt: 2025-01-26T05:38:24.038Z,
    ipAddress: '',
    userAgent: 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Mobile Safari/537.36',
    userId: '6794710450a1fc52d6474d4f'
  },
  user: {
    id: '6794710450a1fc52d6474d4f',
    name: 'Md Faizan',
    email: '[email protected]',
    emailVerified: true,
    image: 'https://lh3.googleusercontent.com/a/ACg8ocLTO1GIpdru812siSWwSB8-oRVBmintHxM44EwhHJdxVwsZUbS5=s96-c',
    createdAt: 2025-01-25T05:05:08.734Z,
    updatedAt: 2025-01-25T05:05:08.734Z
  }
}
--> GET /api/auth/get-session 200 252ms

I tried multiple this things to debug this problem but main change to my axios configration

const axiosInstance = axios.create({
  baseURL: SERVER_DOMAIN, // Backend server URL
  withCredentials: true, // To send cookies with requests
});

I enabled secure cookie in auth.ts thats why i configured next js server for https server

"scripts": {
    "dev": "next dev --turbopack --experimental-https", 
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },

Upvotes: 0

Views: 17

Answers (0)

Related Questions