Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cookie): handle previously set-cookie headers #117

Merged
merged 1 commit into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"];
},
},
);
});
});