Skip to content
Open
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
4 changes: 3 additions & 1 deletion packages/engine.io-client/lib/transports/polling-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ export class Fetch extends Polling {
method: isPost ? "POST" : "GET",
body: isPost ? data : null,
headers,
credentials: this.opts.withCredentials ? "include" : "omit",
// same behavior as XMLHttpRequest: cookies are always sent for same-origin requests, and only with
// `withCredentials: true` for cross-origin requests
credentials: this.opts.withCredentials ? "include" : "same-origin",
}).then((res) => {
// @ts-ignore getSetCookie() was added in Node.js v19.7.0
this.socket._cookieJar?.parseCookies(res.headers.getSetCookie());
Expand Down
46 changes: 45 additions & 1 deletion packages/engine.io-client/test/node.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const path = require("node:path");
const { execFile } = require("node:child_process");
const { Socket } = require("../");
const { Socket, Fetch } = require("../");
const { repeat } = require("./util");
const expect = require("expect.js");
const { parse } = require("../build/cjs/globals.node.js");
Expand Down Expand Up @@ -109,6 +109,50 @@ describe("node.js", () => {
});
});

describe("credentials mode of the fetch() transport", () => {
const originalFetch = globalThis.fetch;
let credentials;

beforeEach(() => {
credentials = [];
globalThis.fetch = (url, init) => {
credentials.push(init.credentials);
return originalFetch(url, init);
};
});

afterEach(() => {
globalThis.fetch = originalFetch;
});

it("should send same-origin cookies with withCredentials: false", (done) => {
const socket = new Socket({
transports: [Fetch],
withCredentials: false,
});

socket.on("open", () => {
// like XMLHttpRequest, and unlike "omit", which drops the cookies of the page origin
expect(credentials).to.eql(["same-origin"]);
socket.close();
done();
});
});

it("should send cross-origin cookies with withCredentials: true", (done) => {
const socket = new Socket({
transports: [Fetch],
withCredentials: true,
});

socket.on("open", () => {
expect(credentials).to.eql(["include"]);
socket.close();
done();
});
});
});

it("should not modify the extraHeaders option with withCredentials: true", (done) => {
const extraHeaders = { foo: "bar" };
const socket = new Socket("http://localhost:3000", {
Expand Down