Gathering detailed insights and metrics for koa-socket-2
Gathering detailed insights and metrics for koa-socket-2
Gathering detailed insights and metrics for koa-socket-2
Gathering detailed insights and metrics for koa-socket-2
npm install koa-socket-2
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (90.99%)
HTML (9.01%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
98 Stars
185 Commits
14 Forks
2 Watchers
1 Branches
1 Contributors
Updated on Jun 27, 2024
Latest Version
2.0.0
Package Id
koa-socket-2@2.0.0
Unpacked Size
43.76 kB
Size
11.42 kB
File Count
14
NPM Version
6.14.5
Node Version
12.18.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
2
Sugar for connecting socket.io to a Koa instance
Koa-socket-2 uses socket.io v3. It is recommended that you connect to a koa-socket-2 server with a socket.io v3 client.
Koa-socket-2 is only compatible with Koa v2 style of middleware (where context is passed as a parameter).
Koa-socket-2 requires Node v7.0.0 or higher.
This project helps you start a SocketIO server using Koa and NodeJS. However, Google's Go language -- or GoLang -- allows you to write code that compiles down to binary. It can be a very good way to take your SocketIO server to the next level by running faster and requiring less overhead than runtime environments like NodeJS.
If you're interested in building a SocketIO server in GoLang, take a look at gosf.io or GOSF on GitHub, the GoLang SocketIO Framework for building SocketIO API servers.
1npm i -S koa-socket-2
Please make the world a better place and stop using unsecure channels. If you absolutely must, however, then the following will get you started.
1const Koa = require('koa'); 2const IO = require('koa-socket-2'); 3 4const app = new Koa(); 5const io = new IO(); 6 7app.use( ... ); 8 9io.attach(app); 10 11io.on('message', (ctx, data) => { 12 console.log('client sent data to message endpoint', data); 13}); 14 15app.listen( process.env.PORT || 3000 );
1const Koa = require('koa'); 2const IO = require('koa-socket-2'); 3const fs = require('fs'); 4 5// If you want to access the HTTPS server from a local JS client for 6// development, then try this simple plugin: 7app.use(async (ctx, next) => { 8 ctx.set('Access-Control-Allow-Origin', 'null'); 9 ctx.set('Access-Control-Allow-Credentials', 'true'); 10 await next(); 11}); 12 13const app = new Koa(); 14const io = new IO(); 15 16app.use( ... ); 17 18// Replace the "..." placeholders below with your own SSL certificate files 19io.attach(app, true, { 20 key: fs.readFileSync(...), 21 cert: fs.readFileSync(...), 22 ca: fs.readFileSync(...) 23}); 24 25console.log('Server: HTTPS/TLS Enabled.'); 26 27io.on('message', (ctx, data) => { 28 console.log('client sent data to message endpoint', data); 29}); 30 31app.listen(process.env.PORT || 3000);
The attach
function is used to attach the IO
instance to the application, this adds server
* and io
properties to the koa application and should happen before the app starts listening on a port.
It also re-maps app.listen
to app.server.listen
, so you could simply do app.listen()
. However if you already had an app.server
attached, it uses it instead and expects you to do app.server.listen()
yourself.
1const Koa = require( 'koa' ); 2const IO = require( 'koa-socket-2' ); 3 4const app = new Koa(); 5const io = new IO(); 6 7// Attach the socket to the application 8io.attach( app ); 9 10// Socket is now available as app.io if you prefer 11app.io.on( event, eventHandler ); 12 13// The raw socket.io instance is attached as app._io if you need it 14app._io.on( 'connection', sock => { 15 // ... 16}); 17 18// *If* you had manually attached an `app.server` yourself, you should do: 19app.listen = function() { 20 app.server.listen.apply(app.server, arguments); 21 return app.server; 22} 23 24// app.listen is mapped to app.server.listen, so you can just do: 25app.listen( process.env.PORT || 3000 );
Middleware can be added in much the same way as it can be added to any regular koa instance.
1io.use( async ( ctx, next ) => { 2 let start = new Date(); 3 await next(); 4 console.log( `response time: ${ new Date() - start }ms` ); 5})
Don't use generator functions. Get with the times, and upgrade to Node >= 7.X.X.
Whilst slightly unwieldy, the standalone method also works
1io.use( ( ctx, next ) => { 2 let start = new Date() 3 return next().then( () => { 4 console.log( `response time: ${ new Date() - start }ms` ) 5 }) 6})
1let ctx = { 2 event: listener.event, 3 data: data, 4 socket: Socket, 5 acknowledge: cb 6}
The context passed to each socket middleware and handler begins the chain with the event that triggered the response, the data sent with that event and the socket instance that is handling the event. There is also a shorthand for firing an acknowledgement back to the client.
As the context is passed to each function in the response chain it is fair game for mutation at any point along that chain, it is up to you to decide whether this is an anti-pattern or not. There was much discussion around this topic for koa v2.
1io.use( async ( ctx, next ) => { 2 ctx.process = process.pid 3 await next() 4}) 5 6io.use( async ( ctx, next ) => { 7 // ctx is passed along so ctx.process is now available 8 console.log( ctx.process ) 9}) 10 11io.on( 'event', ( ctx, data ) => { 12 // ctx is passed all the way through to the end point 13 console.log( ctx.process ) 14})
Namespaces can be defined simply by instantiating a new instance of koaSocket
and passing the namespace id in the constructor. All other functionality works the same, it’ll just be constrained to the single namespace.
1const app = new Koa() 2const chat = new IO({ 3 namespace: 'chat' 4}); 5 6chat.attach( app ); 7 8chat.on( 'message', ctx => { 9 console.log( ctx.data ); 10 chat.broadcast( 'response', ... ); 11});
Namespaces also attach themselves to the app
instance, throwing an error if the property name already exists.
1const app = new Koa(); 2const chat = new IO({ 3 namespace: 'chat' 4}); 5 6chat.attach( app ); 7 8app.chat.use( ... ); 9app.chat.on( ... ); 10app.chat.broadcast( ... );
The attachment is configurable if you don’t want to muddy the app
object with all your namespaces.
1const chat = new IO({ 2 namespace: 'chat', 3 hidden: true 4}); 5 6chat.use( ... ); 7chat.on( ... );
Namespaces are fairly ubiquitous so they get a dirty shorthand for creating them, note that if you want to add any additional options you’ll need to use the longhand object parameter to instantiate koaSocket
.
1const chat = new IO( 'chat' );
Koa app
)Attaches to a koa application
1io.attach( app ); 2app.listen( process.env.PORT );
Function callback
)Applies middleware to the stack.
Middleware are executed each time an event is reacted to and before the callback is triggered for an event.
Middleware with generators should use co.wrap
.
Middleware functions are called with ctx
and next
. The context is passed through each middleware and out to the event listener callback. next
allows the middleware chain to be traversed. Under the hood koa-compose
is used to follow functionality with koa
.
1io.use( async ( ctx, next ) { 2 console.log( 'Upstream' ); 3 await next(); 4 console.log( 'Downstream' ); 5})
String event
, Function callback
)Attaches a callback to an event.
The callback is fired after any middleware that are attached to the instance and is called with the ctx
object and the data
that triggered the event. The data
can also be found on the ctx
, the only potential difference is that data
is the raw data
emitted with the event trigger whilst ctx.data
could have been mutated within the middleware stack.
1io.on( 'message', ( ctx, data ) => { 2 console.log( data ); 3 console.log( ctx.data, data ); 4});
String event
, Function callback
)Removes a callback from an event.
If the event
is omitted then it will remove all listeners from the instance.
If the callback
is omitted then all callbacks for the supplied event will be removed.
1io.off( 'message', onChat ); 2io.off( 'message' ); 3io.off();
String event
, data
)Sends a message to all connections.
String room
).emit( String event
, data
)Sends data to all connections in a room.
1io.to( 'some_room' ).emit( 'message', { hello: 'world' } );
Object adapter
)1const redis = require('socket.io-redis'); 2io.adapter(redis({ host: 'localhost', port: 6379 }));
A list of rooms that this connection is associated with.
1io.on( 'message', ( ctx, data ) => { 2 console.log(ctx.socket.rooms); 3});
String room
)Associates the connection with a room.
1io.on( 'message', ( ctx, data ) => { 2 ctx.socket.join('some_room'); 3});
String room
)Disassociates the connection with a room.
1io.on( 'message', ( ctx, data ) => { 2 ctx.socket.leave( 'some_room' ); 3});
String event
, data
)Sends a message to all active connections except the current connection.
1io.on( 'message', ( ctx, data ) => { 2 ctx.socket.broadcast.emit( 'message', { hello: 'world' } ); 3});
String room
).emit( String event
, data
)Sends a message to all active connections in a room except the current connection.
1io.on( 'message', ( ctx, data ) => { 2 ctx.socket.broadcast.to('some_room').emit( 'message', { hello: 'world' } ); 3});
String event
, data
)Sends a message without ensuring delivery.
1io.on( 'message', ( ctx, data ) => { 2 ctx.socket.volatile.emit( 'message', { hello: 'world' } ); 3});
String event
, data
)Activates per-message compression.
1io.on( 'message', ( ctx, data ) => { 2 ctx.socket.compress(true).emit( 'message', { hello: 'world' } ); 3});
1npm test
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
Found 4/20 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
license file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More