Error with Immutable Headers in Better Auth Session Middleware on Deno Server

Guys


Hello ,

I’m working on setting up session management using Better Auth with a Deno server and Hono as the framework. I followed the documentation to create a middleware for session handling, but I'm running into an issue when trying to retrieve sessions.

Here’s a simplified version of my code:

import { type Context, type Next } from "@hono/hono";
import { auth } from "../auth.ts"; // Import Better Auth instance

export const sessionMiddleware = async (c: Context, next: Next) => {
  try {
    var headers = c.req.raw.headers;
    // @ts-ignore
    const session = await auth.api.getSession({ headers });

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

    c.set("user", session.user);
    c.set("session", session.session);
    return next();
  } catch (error) {
    console.error("Error in sessionMiddleware:", error);
    // Return a 500 response if an error occurs
    return c.json({ error: "Failed to retrieve session" }, 500);
  }
};

export default sessionMiddleware;


Issue Details


Upon running the server, I receive the following error:

Listening on http://localhost:8087/
Error in sessionMiddleware: TypeError: Cannot change headers: headers are immutable
    at Headers.set (ext:deno_fetch/20_headers.js:425:13)
    at Object.handler (file:///C:/Users/jacks/AppData/Local/deno/npm/registry.npmjs.org/better-auth/0.6.2/dist/plugins.js:1:38396)
    ...


The error occurs when the getSession method is called, indicating that headers are treated as immutable. I attempted the workaround of using raw headers directly from c.req.raw.headers, but this hasn’t resolved the issue.

Environment


  • Deno: 2.0.2
  • Better Auth: v0.6.2
  • Hono: v4.6.8
image.png
Was this page helpful?