vvo / iron-session

πŸ›  Secure, stateless, and cookie-based session library for JavaScript

Home Page:https://get-iron-session.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

res.headers.append is not a function

LeeBrooks3 opened this issue Β· comments

Hi πŸ‘‹

Leveraging iron-session for our Next.js app (v13.4.2) authentication works beautifully locally - however, once it was deployed to AWS via SST (v2.11.1) we encountered res.headers.append is not a function when calling await session.save().

See:

res.headers.append("set-cookie", cookieValue);

Upon inspection, when running locally via next dev, headers is undefined and therefore the session cookie is set via res.setHeader on line 238 - and all works great πŸ₯³ - whereas when running via AWS, headers is an empty object ({}) and an exception is therefore being thrown when trying to append the session cookie header via res.headers.append on line 229 - πŸ˜”.

Perhaps an assumption has been made around the shape / type of req and an extra check could be valuable?

Many thanks in advance ✌️

Here's a workaround for anybody looking:

import { IronSessionOptions } from "iron-session";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";

export function withSessionRoute(handler: NextApiHandler, sessionOptions: IronSessionOptions) {
    return function (req: NextApiRequest, res: NextApiResponse) {
        if ("headers" in res && !("append" in (res.headers as {}))) {
            Object.defineProperty(res.headers, "append", {
                value: res.setHeader,
            });
        }

        return withIronSessionApiRoute(handler, sessionOptions)(req, res);
    };
}
commented

Same issue few hours ago! Thank you kind stranger for your snipped πŸ’™

Previous error got fixed, however, I'm facing new message (using NextJS behind Serverless-Http on Lambda).

{
    "error": "Error occured! Cannot set property headers of #<ServerlessResponse> which has only a getter"
}

This time seems like it's coming from serverless-http.

Exactly the same problem for me. I'm trying to switch from AWS Amplify, which is catastrophic but works, to SST, which produces this problem.

commented

@shankiflang as alternative, Next-Auth works fine with SST.

@shankiflang as alternative, Next-Auth works fine with SST.

We've already tried, but Next-Auth isn't what we need. Iron-session is perfect ATM on Amplify. We can't understand why it doesn't work with SST.