socket.io running in a webworker.
ensures timers/heartbeat mechanisms work regardless.
Serve the Socket.IO browser client and pass that URL as lib.
The page only needs the worker proxy script:
<scriptsrc="/socketio-worker.js"></script>The worker does not inspect page script tags.
constio=newSocketIOWorker({src: '/socketio-worker.js',lib: '/socket.io/socket.io.js',url: 'https://example.com',options: {autoConnect: false,transports: ['websocket']}})awaitio.set({auth: {token: 'foo'},query: {room: 'bar'}}).connect()io.on('connect',patch=>console.log(patch.transport))io.on('disconnect',patch=>console.log(patch.disconnected))io.on('connect_error',(_,message)=>console.log(message.value))io.on('example:event',payload=>console.log(payload))awaitio.emit('example:event',{ok: true})awaitio.close()Lifecycle listeners receive (patch, message):
patch— connection snapshot (connected,transport, etc.)message.value— cause forconnect_error/disconnect
Note
- Use
set(path, value)orset(object)for Socket.IO mutations.
Normal Socket.IO assignment is synchronous; worker-owned mutation must cross the proxy boundary. - Async calls are chainable; await the final call.
Use emitWithAck() when the server must respond:
constack=awaitio.emitWithAck('update item','1',{name: 'updated'})- Payloads, call args, and method results use Socket.IO JSON serialization.
undefinedfollows Socket.IO behavior: array slots becomenull, object fields are omitted.- Callback acks, like
emit(..., callback), are not implemented. - Use
set(path, value)orset(object)for Socket.IO mutations.
Direct proxy mutations like:io.auth.token = 'abc'are local only. - Use
close()for graceful cleanup;terminate()is immediate.
npm i
npm t