Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

sockjs-client

sockjs10mMIT1.6.1TypeScript support: definitely-typed

SockJS-client is a browser JavaScript library that provides a WebSocket-like object.

websockets, websocket

readme

SockJS-client

npm versionDependenciesChatContributor Covenant BrowserStack Status

SockJS for enterprise

Available as part of the Tidelift Subscription.

The maintainers of SockJS and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Summary

SockJS is a browser JavaScript library that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server.

Under the hood SockJS tries to use native WebSockets first. If that fails it can use a variety of browser-specific transport protocols and presents them through WebSocket-like abstractions.

SockJS is intended to work for all modern browsers and in environments which don't support the WebSocket protocol -- for example, behind restrictive corporate proxies.

SockJS-client does require a server counterpart:

Philosophy:

  • The API should follow HTML5 Websockets API as closely as possible.
  • All the transports must support cross domain connections out of the box. It's possible and recommended to host a SockJS server on a different server than your main web site.
  • There is support for at least one streaming protocol for every major browser.
  • Streaming transports should work cross-domain and should support cookies (for cookie-based sticky sessions).
  • Polling transports are used as a fallback for old browsers and hosts behind restrictive proxies.
  • Connection establishment should be fast and lightweight.
  • No Flash inside (no need to open port 843 - which doesn't work through proxies, no need to host 'crossdomain.xml', no need to wait for 3 seconds in order to detect problems)

Subscribe to SockJS mailing list for discussions and support.

SockJS family

Work in progress:

Getting Started

SockJS mimics the WebSockets API, but instead of WebSocket there is a SockJS Javascript object.

First, you need to load the SockJS JavaScript library. For example, you can put that in your HTML head:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

After the script is loaded you can establish a connection with the SockJS server. Here's a simple example:

 var sock = new SockJS('https://mydomain.com/my_prefix');
 sock.onopen = function() {
     console.log('open');
     sock.send('test');
 };

 sock.onmessage = function(e) {
     console.log('message', e.data);
     sock.close();
 };

 sock.onclose = function() {
     console.log('close');
 };

SockJS-client API

SockJS class

Similar to the 'WebSocket' API, the 'SockJS' constructor takes one, or more arguments:

var sockjs = new SockJS(url, _reserved, options);

url may contain a query string, if one is desired.

Where options is a hash which can contain:

  • server (string)

    String to append to url for actual data connection. Defaults to a random 4 digit number.

  • transports (string OR array of strings)

    Sometimes it is useful to disable some fallback transports. This option allows you to supply a list transports that may be used by SockJS. By default all available transports will be used.

  • sessionId (number OR function)

    Both client and server use session identifiers to distinguish connections. If you specify this option as a number, SockJS will use its random string generator function to generate session ids that are N-character long (where N corresponds to the number specified by sessionId). When you specify this option as a function, the function must return a randomly generated string. Every time SockJS needs to generate a session id it will call this function and use the returned string directly. If you don't specify this option, the default is to use the default random string generator to generate 8-character long session ids.

    • timeout (number)

    Specify a minimum timeout in milliseconds to use for the transport connections. By default this is dynamically calculated based on the measured RTT and the number of expected round trips. This setting will establish a minimum, but if the calculated timeout is higher, that will be used.

Although the 'SockJS' object tries to emulate the 'WebSocket' behaviour, it's impossible to support all of its features. An important SockJS limitation is the fact that you're not allowed to open more than one SockJS connection to a single domain at a time. This limitation is caused by an in-browser limit of outgoing connections - usually browsers don't allow opening more than two outgoing connections to a single domain. A single SockJS session requires those two connections - one for downloading data, the other for sending messages. Opening a second SockJS session at the same time would most likely block, and can result in both sessions timing out.

Opening more than one SockJS connection at a time is generally a bad practice. If you absolutely must do it, you can use multiple subdomains, using a different subdomain for every SockJS connection.

Supported transports, by browser (html served from http:// or https://)

Browser Websockets Streaming Polling
IE 6, 7 no no jsonp-polling
IE 8, 9 (cookies=no) no xdr-streaming † xdr-polling †
IE 8, 9 (cookies=yes) no iframe-htmlfile iframe-xhr-polling
IE 10 rfc6455 xhr-streaming xhr-polling
Chrome 6-13 hixie-76 xhr-streaming xhr-polling
Chrome 14+ hybi-10 / rfc6455 xhr-streaming xhr-polling
Firefox <10 no ‡ xhr-streaming xhr-polling
Firefox 10+ hybi-10 / rfc6455 xhr-streaming xhr-polling
Safari 5.x hixie-76 xhr-streaming xhr-polling
Safari 6+ rfc6455 xhr-streaming xhr-polling
Opera 10.70+ no ‡ iframe-eventsource iframe-xhr-polling
Opera 12.10+ rfc6455 xhr-streaming xhr-polling
Konqueror no no jsonp-polling
  • : IE 8+ supports XDomainRequest, which is essentially a modified AJAX/XHR that can do requests across domains. But unfortunately it doesn't send any cookies, which makes it inappropriate for deployments when the load balancer uses JSESSIONID cookie to do sticky sessions.

  • : Firefox 4.0 and Opera 11.00 and shipped with disabled Websockets "hixie-76". They can still be enabled by manually changing a browser setting.

Supported transports, by browser (html served from file://)

Sometimes you may want to serve your html from "file://" address - for development or if you're using PhoneGap or similar technologies. But due to the Cross Origin Policy files served from "file://" have no Origin, and that means some of SockJS transports won't work. For this reason the SockJS transport table is different than usually, major differences are:

Browser Websockets Streaming Polling
IE 8, 9 same as above iframe-htmlfile iframe-xhr-polling
Other same as above iframe-eventsource iframe-xhr-polling

Supported transports, by name

Transport References
websocket (rfc6455) rfc 6455
websocket (hixie-76) draft-hixie-thewebsocketprotocol-76
websocket (hybi-10) draft-ietf-hybi-thewebsocketprotocol-10
xhr-streaming Transport using Cross domain XHR streaming capability (readyState=3).
xdr-streaming Transport using XDomainRequest streaming capability (readyState=3).
eventsource EventSource/Server-sent events.
iframe-eventsource EventSource/Server-sent events used from an iframe via postMessage.
htmlfile HtmlFile.
iframe-htmlfile HtmlFile used from an iframe via postMessage.
xhr-polling Long-polling using cross domain XHR.
xdr-polling Long-polling using XDomainRequest.
iframe-xhr-polling Long-polling using normal AJAX from an iframe via postMessage.
jsonp-polling Slow and old fashioned JSONP polling. This transport will show "busy indicator" (aka: "spinning wheel") when sending data.

Connecting to SockJS without the client

Although the main point of SockJS is to enable browser-to-server connectivity, it is possible to connect to SockJS from an external application. Any SockJS server complying with 0.3 protocol does support a raw WebSocket url. The raw WebSocket url for the test server looks like:

  • ws://localhost:8081/echo/websocket

You can connect any WebSocket RFC 6455 compliant WebSocket client to this url. This can be a command line client, external application, third party code or even a browser (though I don't know why you would want to do so).

Deployment

You should use a version of sockjs-client that supports the protocol used by your server. For example:

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

For server-side deployment tricks, especially about load balancing and session stickiness, take a look at the SockJS-node readme.

Development and testing

SockJS-client needs node.js for running a test server and JavaScript minification. If you want to work on SockJS-client source code, checkout the git repo and follow these steps:

cd sockjs-client
npm install

To generate JavaScript, run:

gulp browserify

To generate minified JavaScript, run:

gulp browserify:min

Both commands output into the build directory.

Testing

Automated testing provided by:

Once you've compiled the SockJS-client you may want to check if your changes pass all the tests.

npm run test:browser_local

This will start karma and a test support server.

Browser Quirks

There are various browser quirks which we don't intend to address:

  • Pressing ESC in Firefox, before Firefox 20, closes the SockJS connection. For a workaround and discussion see #18.
  • jsonp-polling transport will show a "spinning wheel" (aka. "busy indicator") when sending data.
  • You can't open more than one SockJS connection to one domain at the same time due to the browser's limit of concurrent connections (this limit is not counting native WebSocket connections).
  • Although SockJS is trying to escape any strange Unicode characters (even invalid ones - like surrogates \xD800-\xDBFF or \xFFFE and \xFFFF) it's advisable to use only valid characters. Using invalid characters is a bit slower, and may not work with SockJS servers that have proper Unicode support.
  • Having a global function called onmessage or such is probably a bad idea, as it could be called by the built-in postMessage API.
  • From SockJS' point of view there is nothing special about SSL/HTTPS. Connecting between unencrypted and encrypted sites should work just fine.
  • Although SockJS does its best to support both prefix and cookie based sticky sessions, the latter may not work well cross-domain with browsers that don't accept third-party cookies by default (Safari). In order to get around this make sure you're connecting to SockJS from the same parent domain as the main site. For example 'sockjs.a.com' is able to set cookies if you're connecting from 'www.a.com' or 'a.com'.
  • Trying to connect from secure "https://" to insecure "http://" is not a good idea. The other way around should be fine.
  • Long polling is known to cause problems on Heroku, but a workaround for SockJS is available.
  • SockJS websocket transport is more stable over SSL. If you're a serious SockJS user then consider using SSL (more info).

changelog

1.6.1

Fixes

  • Update eventsource to 2.0.2 due to CVE-2022-1650. Fixes #590
  • Update minimist to 1.2.6. Fixes #585

1.6.0

Fixes

  • Remove agent: false to allow usage of globalAgent. Fixes #421

dependencies

  • Update url-parse due to CVE-2022-0686, CVE-2022-0639, and CVE-2022-0512. Fixes #576
  • Remove json3 dependency. Fixes #476
  • Update eventsource to 1.1.0
  • Update faye-websocket to 0.11.4
  • Update debug to 3.2.7

devDependencies

  • Update follow-redirects (devDep) due to CVE-2022-0536 and CVE-2022-0155
  • Update karma (devDep) due to CVE-2022-0437
  • Update cached-path-relative (devDep) due to CVE-2021-23518
  • Update fsevents (devDep) to fix:
    • ini CVE-2020-7788
    • minimist CVE-2020-7598
    • tar CVE-2021-37713, CVE-2021-37701, CVE-2021-32804, CVE-2021-32803
  • Update copy-props (devDep) due to CVE-2020-28503
  • Update eslint, mocha, gulp-replace, karma-browserify, gulp-sourcemaps, and browserify

Other Changes

  • Remove bower
  • Remove Travis CI
  • Require Node.js 12

1.5.2

  • Update url-parse due to CVE-2021-3664.

1.5.1

  • Update url-parse due to CVE-2021-27515.

1.5.0

  • Update url-parse, kind-of, minimist, websocket-extensions due to security vulnerabilies.
  • Update dev dependencies.
  • Allow loopback address hostnames on a secure page. Fixes #486
  • Enable eventsource transport for node.js clients.

1.4.0

  • Add timeout option to set a minimum transport timeout. Fixes #403
  • Update dev deps to fix security warnings from npm audit
  • Guard against null this._transport in debug statement. Fixes #448

1.3.0

  • Revert debug to ^3 because v4 starts using ES6. Fixes #457

1.2.0

  • Update all outdated dependencies
  • Switch to karma and browserstack for running automated browser tests

1.1.5

  • Wrap the the contentWindow access in a try/catch block when in setTimeout #363
  • Revised example in README #356
  • Fix connection close when Transport timeout #358
  • Fixed crash with react-native@0.45.1 on Android #386
  • Update jsDelivr link #404, #405
  • Remove Sauce Labs unsupported browsers
  • Add link to rust server implementation #411
  • location.protocol should include final : #396

1.1.4

  • Upgrade debug and fix object key literal mangling, fixes regression in Opera 11.10 #359
  • Trim descriptions in package.json and bower.json - #372

1.1.3

  • Bad publish to NPM (removed)

1.1.2

  • Ensure both sender and receiver are cleaned upon close - #342
  • Remove event listeners before calling close - #344
  • Update documentation links - #351, #339, #316
  • Explicitly export undefined when WebSocket does not exist. Fixes Webpack. #321
  • Include dist folder on npm - #265
  • Simplify build setup
  • Update to Node.js 6.9
  • Add sourcemap for minified version
  • Remove unused String.trim shim

1.1.1

  • Do not pass protocols or options arguments to browser WebSocket constructor - #309

1.1.0

  • Fix IE7/8 usage of console.log which does not have apply - #279
  • Remove dbg global variable - #282
  • Bump faye-websocket version to 0.11.0 - #267
  • Optimize arguments usage - #263
  • Add sourcemap file to dist folder - #237
  • Add way to transparently pass transport-specific options - #272

1.0.3

  • Use https module for xhr requests in node when url uses https - #254

1.0.2

  • Fix iframe info receiver url
  • Move iframe.contentWindow check inside setTimeout - #246

1.0.1

  • Use proper base url for iframe-based info receiver - #249
  • Don't register unload event in chrome packaged app - #223
  • Allow custom session ids - #250
  • Remove version property from bower.json - #247
  • Update example CDN url - #244

1.0.0

  • Simplify url handling by delegating to url-parse - #242
  • Upgrade to url-parse 1.0.1 to fix colon issue if auth has no password

1.0.0-beta.13

  • Transport timeout on connection should fallback - #238

1.0.0-beta.12

  • Upgrade url-parse to 1.0.0 to fix #218 again

1.0.0-beta.10

  • Upgrade url-parse to 0.2.3 to fix #222

1.0.0-beta.9

  • Upgrade url-parse to 0.2.1 to fix 'too much recursion' errors

1.0.0-beta.8

  • Upgrade url-parse to 0.2.0 to fix inheritance issues

1.0.0-beta.7

  • Upgrade url-parse to 0.1.5 to fix #218
  • Don't strip basic auth from url - #219

1.0.0-beta.6

  • Upgrade url-parse to 0.1.3 to avoid CSP issues

1.0.0-beta.5

  • Upgrade url-parse to 0.1.1 to fix #214

1.0.0-beta.4

  • Upgrade url-parse to 0.1.0 and sockjs to 0.3.11
  • Update .npmignore

1.0.0-beta.3

  • Move debug from devDependencies to dependencies

1.0.0-beta.2

  • Relax requirements when using same origin XHR - #80
  • Upgrade to JSON3 from JSON2 - #123
  • Package library with browserify supporting the UMD pattern - #184
  • Move tests to JavaScript
  • Add Gulp.js build script
  • Fix getOrigin for file:/// urls and standard ports - #173
  • Add onerror event handlers to Websockets - #169
  • Increase RTO lower bound to prevent spurious timeouts on IE8/9 - #161
  • Use window.crypto for random values when available - #128
  • Fix handling of listeners added and removed mid-dispatch - #127
  • Fix XHR Streaming for IE8 - #83
  • Remove explicit AMD name - #107
  • Check for an empty response from /info request - #143
  • Add Content-Type to XHR requests to fix issue over HTTPS on Galaxy S4 - #164
  • Fix iframe fallback when message is sent from a popup in IE7/8 - #166
  • Add support for query strings on the url - #72
  • Now works inside of Web Workers - #181
  • Support EventSource / Server Sent Events outside of iframes - #201
  • Rename protocols to transports - #65
  • Allow transports which need the body to trigger on 'interactive' readyState - #175
  • try/catch access to document.domain - #187
  • Use window.location instead of document.location - #195
  • Allow usage from node.js with same API

0.3.4

  • Mentioned njoyce's fork of sockjs-gevent.
  • 90 - Don't catch onbeforeunload event - it breaks javascript://

    links in IE.
  • IE mangles 204 response code for 1223 on ajax, see: http://bugs.jquery.com/ticket/1450
  • Make new optional for SockJS constructor (via substack).
  • It is impossible to cancel JSONP polling request - compensate for that.
  • Refactored EventEmitter prototype (used only internally)
  • 66 - Failure to post data to /xhr_send should kill the session

0.3.2

  • 77 - Getting /info on modern browsers when html is served from

      file:// urls was broken.

0.3.1

  • 61 - Meteor guys found that we unintentionally catch "onopen" errors.

  • 63 - Meteorjs guys found that xhr-streaming on Safari sometimes

    left busy cursor running.
  • Increased allowed time for websocket transport (from 1 rtt to 2), this should make ws transport more reliable over SSL, at the cost of slightly longer connection time for users with blocked ws.
  • 57 - previous fix didn't really work, sockjs-client still left

    a mess in browsers history when using iframe transports. This is fixed now.
  • 60 - Opera 12 (next) claims to do AJAX2 / CORS, but can't

    do xhr-streaming.
  • 58 - onunload test sometimes failed on Safari on windows

  • Updated readme WRT websocket protocols
  • Updated readme WRT deployments on heroku
  • Add minimalistic license block to every source file.

0.3.0

  • Temporarily disabled iframe tests - they are failing unpredictably.
  • 57 - pointing an iframe to "about:blank" during cleanup caused

    Opera to messup history.
  • 55 - Improved iframe abstraction (reduced a possible mem leak)

  • Refactored AJAX abstractions, for better CORS handing - again.
  • Add additional parent origin security check to an iframe.
  • Urls with hashes or query strings can't be passed to SockJS.
  • 18 - Mention workaround for Firefox ESC key issue

  • 53 - AMD compliance

  • sockjs/sockjs-protocol#28 - always use square brackets for websocket frames
  • 51 - initial support for IE10 - try XHR before XDR

  • 28 - handle onunload / onbeforeunload in a more robust fashion

  • 49 - support SockJS-client being used from files served from

    file:// urls.

0.2.1

  • "smoke-latency.html" test was unnecesairly sending too much data.
  • Bumped core dependencies (coffee-script and uglify-js)
  • Minor updates to the README, few cosmetic changes in the code.

0.2.0

  • The API had changed - use protocols_whitelist option instead of passing an array of protocols as a second argument to SockJS constructor.
  • Dropped 'chunking-test' functionality and replace it with 'info'.
  • Rewritten protocol-choosing alogirthm, see "utils.detectProtocols" method.
  • Use dynamic protocol timeouts based on RTT, not hardcoded 5 seconds
  • 34 - Don't ever reuse session_id, especially when trying

    fallback protocols.
  • The test server got moved from SockJS-client to SockJS-node.
  • Don't test unicode surrogates - it can't work in some environments.
  • XHR/XDR helpers were rewritten, ajax transports were simplified.
  • Added a domain check in the iframe to improve security.
  • SockJS will now trigger 1002 error if there is a problem during handshake instead of 2000 error.
  • Smoke-throughput test is renamed to smoke-latency.

0.1.2

  • 29 - Allow all unicode characters to be send over SockJS.

  • 15 - SockJS should now work fine even if the connection is started

    in HEAD, before BODY is loaded.
  • 28 - In rare circumstances WebSocket connection can be left intact

    after the page is unloaded in FireFox.
  • Updated scripts to work with Node 0.6.
  • Initial work to do better QUnit testing.
  • Updated the minifying script (always escape unicode chars, remove trailing comment).
  • Use string instead of array of chars (utils.js:random_number_string).

0.1.1

  • 21 Get JsonP transport working on IE9 (Vladimir Dronnikov).

  • 26 Emit heartbeat event.

  • 27 Include license inline.

0.1.0

  • SockJS-client can only send UTF-8 encodable strings. Previously we took advantage of rich data structures and automatically json-encoded them, but this got removed. Now, all data passed to send will be converted to string. This is also how native
  • status property on EventClose is renamed to code as per Websocket API WebSockets behave.
  • The test server was updated to new sockjs-node API
  • Fixed problem with Jsonp-polling transport on IE9
  • Repository was moved - updated links.

0.0.4

  • All transports were refactored, some transports were introduced: htmlfile and separate xhr-streaming.
  • Added logic to detect support for http chunking, and thus a possibility to rule out streaming transports before running them.
  • Added 'cookie' option, useful for cookie-based load balancing (currently, it make a difference only for IE).
  • Added hack to prevent EventSource from crashing Safari and Chrome.
  • Loads and loads of other small and medium changes.

0.0.2

  • Initial support for JSESSIONID based load balancing. Currently doesn't play nicely with IE XDomainRequest transport.

0.0.1

  • Initial release.