Skip to content

Issue: Unable to call session.save() inside Next.js Middleware due to Edge runtime API mismatch #938

@AminKubiyax

Description

@AminKubiyax

Summary

Attempting to use iron-session inside src/middleware.ts in a Next.js 14+ app causes a runtime error:

TypeError: res.getHeader is not a function

This happens when calling session.save().

Why This Happens

Next.js middleware always runs in the Edge runtime, where:

  • req is a Web Fetch API Request, not IncomingMessage
  • res is a NextResponse, not ServerResponse
  • Edge responses do not implement getHeader / setHeader

iron-session internally assumes Node.js-style response objects when saving a session cookie, which leads to the crash.

Expected Behavior

It should be possible to:

  • write sessions in middleware, or
  • at least fail gracefully, or
  • provide an official Edge-compatible API (previously iron-session/edge existed).

Actual Behavior

Calling session.save() from middleware always throws:

TypeError: res.getHeader is not a function

This blocks:

  • sliding TTL/session refresh in middleware
  • consistent session handling across middleware + API routes

Reproduction

// middleware.ts
import { NextResponse } from "next/server";
import { getIronSession } from "iron-session";

export function middleware(req) {
  const res = NextResponse.next();
  const session = await getIronSession(req, res, options);

  session.lastActive = Date.now();
  await session.save(); // CRASH! - res.getHeader is not a function

  return res;
}

What would help

  • Clarify whether iron-session officially supports middleware.ts
  • Provide an Edge runtime–safe API
  • Or document a recommended next.js middleware pattern for session TTL refresh, if unsupported

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions