EventSource Polyfill
eventsource-polyfill provides a robust client-side polyfill for the W3C EventSource API, enabling Server-Sent Events (SSE) functionality in web browsers that lack native support, particularly older environments like Internet Explorer 8+ and Android browser 2.1+. The package aims to bridge the compatibility gap, ensuring that web applications can leverage SSE streams consistently across diverse browser landscapes. While the project saw its last significant update with version 0.9.7 in 2017, which addressed a critical bug related to 'data' events, its release cadence has ceased, indicating an abandoned status. Developers should be aware it's designed exclusively for browser applications, modifying the global window.EventSource object, and will not receive further updates or new features.
Common errors
-
ReferenceError: EventSource is not defined
cause Attempting to use `EventSource` in a Node.js environment or before the polyfill has been loaded in a browser.fixEnsure the polyfill is imported and bundled for a browser target. For Node.js, use a native SSE client library. -
Uncaught SyntaxError: Cannot use import statement outside a module
cause Using ESM `import` syntax in a CommonJS module or an environment not configured for ES modules (e.g., older Browserify setups without appropriate transforms).fixIf using CommonJS, use `require('eventsource-polyfill');`. If using ES modules, ensure your project is configured for `type: 'module'` in `package.json` or uses a bundler like Webpack/Rollup with proper ESM handling.
Warnings
- breaking Versions prior to 0.9.7 contained a critical bug where an event named 'data' would cause an infinite loop in the polyfill, leading to application unresponsiveness.
- gotcha This polyfill is strictly for client-side browser environments and will not function correctly in Node.js or other non-browser JavaScript runtimes.
- gotcha The `eventsource-polyfill` project is abandoned, with its last update in 2017. It will not receive new features, bug fixes for modern browser issues, or security patches.
Install
-
npm install eventsource-polyfill -
yarn add eventsource-polyfill -
pnpm add eventsource-polyfill
Imports
- Polyfill Activation (ESM)
import { EventSource } from 'eventsource-polyfill';import 'eventsource-polyfill';
- Polyfill Activation (CJS)
const EventSource = require('eventsource-polyfill');require('eventsource-polyfill');
Quickstart
import 'eventsource-polyfill'; // Ensure polyfill is loaded
function setupEventSource() {
if (typeof window === 'undefined' || typeof EventSource === 'undefined') {
console.warn('EventSource is not available in this environment or not polyfilled.');
return;
}
// Replace with your actual SSE endpoint
const eventSourceUrl = 'https://example.com/stream'; // Or a mock API if running locally
console.log(`Attempting to connect to EventSource at ${eventSourceUrl}`);
const es = new EventSource(eventSourceUrl);
es.onopen = () => {
console.log('EventSource connection opened.');
};
es.onmessage = (event) => {
console.log('Received message:', event.data);
// You can parse JSON if your events are JSON strings
try {
const data = JSON.parse(event.data);
console.log('Parsed JSON data:', data);
} catch (e) {
// Not JSON
}
};
es.addEventListener('customEvent', (event: MessageEvent) => {
console.log('Received custom event "customEvent":', event.data);
});
es.onerror = (error) => {
console.error('EventSource error:', error);
// Attempt to reconnect after a delay, or close if critical
es.close();
console.log('EventSource closed due to error. Reconnecting in 5 seconds...');
setTimeout(setupEventSource, 5000);
};
// Close the connection after some time or based on user action
setTimeout(() => {
es.close();
console.log('EventSource connection closed after 30 seconds.');
}, 30000);
}
setupEventSource();