Skip to content

Commit

Permalink
fix: change credentials mode from "omit" to "same-origin" when set to…
Browse files Browse the repository at this point in the history
… false

Signed-off-by: Lukas Reining <[email protected]>
  • Loading branch information
lukas-reining committed Dec 15, 2024
1 parent 6e35837 commit 3e87ce9
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/eventsource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ export type EventSourceOptions = {
* Fetch implementation to use for connecting. Defaults to {@link globalThis.fetch}
*/
fetch?: typeof fetch;

/**
* Sets the fetch credentia mode to omit instead of same-site.
* If {@link EventSourceInit.withCredentials} is set, this option will take precedence.
*/
omitCredentials?: boolean;
} & Omit<RequestInit, 'cache' | 'credentials' | 'signal'>;

/**
Expand All @@ -40,9 +46,9 @@ export type EventSourceExtraOptions = {
fetchInput?: typeof fetch;
};

export type CustomEvent = Event & {
response?: Response;
};
export type CustomEvent = Event & {
response?: Response;
};

export class CustomEventSource extends EventTarget implements EventSource {
// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-url
Expand Down Expand Up @@ -93,6 +99,12 @@ export class CustomEventSource extends EventTarget implements EventSource {
this.logger = this.options.logger ?? new ConsoleLogger();
}

if (this.options.omitCredentials && this.options.withCredentials) {
this.logger?.warn(
'omitCredentials and withCredentials have been set to true. withCredentials will be ignored and credentials will not be sent!',
);
}

this.connect();
}

Expand Down Expand Up @@ -131,7 +143,11 @@ export class CustomEventSource extends EventTarget implements EventSource {
Accept: ContentTypeEventStream,
},
cache: 'no-store',
credentials: this.withCredentials ? 'include' : 'omit',
credentials: this.options.omitCredentials
? 'omit'
: this.withCredentials
? 'include'
: 'same-origin',
signal: this.abortController?.signal,
};

Expand All @@ -157,7 +173,10 @@ export class CustomEventSource extends EventTarget implements EventSource {
response,
);
} else if (!response?.body) {
return this.failConnection(`Request failed with empty response body'`, response);
return this.failConnection(
`Request failed with empty response body'`,
response,
);
}

this.announceConnection(response);
Expand Down

0 comments on commit 3e87ce9

Please sign in to comment.