Skip to content

Commit

Permalink
fix(cookie): handle previously set-cookie headers (#117)
Browse files Browse the repository at this point in the history
This commit fixes a case where previous set-cookie headers were ignored through
the request lifecycle. This is now fixed and handles both single and multiple
set-cookie header values. Since in Node.js you can do:

res.setHeader("set-cookie", "name=value"); and
res.setHeader("set-cookie", ["name=value", "name2=value2"])

fixes #112
  • Loading branch information
vvo committed May 26, 2020
1 parent 774f300 commit 81c156d
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ export async function applySession(
`next-iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it`,
);
}
res.setHeader("set-cookie", [cookieValue]);
const existingSetCookie = [res.getHeader("set-cookie") || []].flat();
res.setHeader("set-cookie", [...existingSetCookie, cookieValue]);
return cookieValue;
},
destroy() {
Expand Down
53 changes: 53 additions & 0 deletions lib/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ test("req.session.save creates a seal and stores it in a cookie", () => {
},
{
setHeader: jest.fn(),
getHeader: jest.fn(),
},
);
});
Expand Down Expand Up @@ -242,6 +243,7 @@ test("When ttl is 0, maxAge have a specific value", () => {
},
{
setHeader: jest.fn(),
getHeader: jest.fn(),
},
);
});
Expand Down Expand Up @@ -619,3 +621,54 @@ test("it throws when cookie length is too big", () => {
);
});
});

test("it handles previously set cookies (single value)", () => {
return new Promise((done) => {
const handler = async (req, res) => {
await req.session.save();

const headerValue = res.setHeader.mock.calls[0][1];
expect(headerValue.length).toBe(2);
expect(headerValue[0]).toBe("existingCookie=value");
done();
};
const wrappedHandler = withIronSession(handler, { password, cookieName });
wrappedHandler(
{
headers: { cookie: "" },
},
{
setHeader: jest.fn(),
getHeader: function () {
return "existingCookie=value";
},
},
);
});
});

test("it handles previously set cookies (multiple values)", () => {
return new Promise((done) => {
const handler = async (req, res) => {
await req.session.save();

const headerValue = res.setHeader.mock.calls[0][1];
expect(headerValue.length).toBe(3);
expect(headerValue[0]).toBe("existingCookie=value");
expect(headerValue[1]).toBe("anotherCookie=value2");
done();
};
const wrappedHandler = withIronSession(handler, { password, cookieName });
wrappedHandler(
{
headers: { cookie: "" },
},
{
setHeader: jest.fn(),
getHeader: function () {
return ["existingCookie=value", "anotherCookie=value2"];
},
},
);
});
});

0 comments on commit 81c156d

Please sign in to comment.