Troubleshooting user session issues in Hono/Node backend with Next.js frontend

I’m having trouble with user sessions in my app. The backend uses Hono with Node and better-auth, while the frontend is Next.js.

Here’s what’s happening:

  • My ‘/user/session’ endpoint returns null
  • The middleware shows the correct session info
  • I’ve set up CORS and enabled secure cookies
  • Axios is configured with withCredentials: true
  • Next.js is running with experimental HTTPS

I’ve tried debugging but can’t figure out why the session is null on the client side. The server logs indicate that the session exists. Could there be an issue with how the session data is transferred from the backend to the frontend?

// Example of current setup
const app = new Hono();
app.use(addSession);

const sessionRoute = new Hono();
sessionRoute.get('/current', (c) => {
  const userInfo = c.get('user');
  return userInfo ? c.json(userInfo) : c.body(null, 401);
});

// Frontend function to retrieve session data
const getSession = async () => {
  const response = await axiosInstance.get('/user/current');
  return response.data;
};

What else should I check to resolve this?

Have you checked if your authentication cookies are being properly set and transmitted? One common issue with cross-origin requests is that cookies might not be included by default. Ensure your backend is setting the ‘SameSite’ attribute correctly on your session cookies. For cross-origin requests, you might need ‘SameSite=None; Secure’.

Also, verify that your Next.js app is correctly handling the received cookies. Sometimes, the issue lies in how the frontend manages and stores session data. You might want to use a tool like the browser’s Network tab to inspect the requests and responses, checking if the cookies are present and being sent correctly.

Lastly, double-check your CORS configuration. Ensure it’s not just allowing the origin but also credentials. On the server-side, you might need to set ‘credentials: true’ in your CORS options.

hey, have u checked ur axios config? sometimes the withCredentials setting can be tricky. also, make sure ur server is sending the right headers for CORS. i had a similar issue and it turned out my server wasnt allowing credentials properly. double-check ur cors config on the backend too, it might need tweaking

hmm, have u tried checking the network tab in ur browser’s dev tools? it can show u exactly what’s being sent and received. maybe the session cookie isn’t making it to the client? also, are u using httpOnly cookies? those can be tricky with js. what about trying a different auth method, like jwt tokens? just some ideas to explore :thinking: