Search code examples
koakoa2

Is there analog of express's app.set( 'something', something ) in koa?


I need socket.io instance in several places in my app. To achieve this in express i can do this:

app.set('io', io);

In koa right now i have this:

app.use( async ( ctx, next ) => {
   ctx.io = io;
   await next();
 });

This works, but this middleware executes every time my server recieves request. Is there a better way to do this?


Solution

  • I don't know how you are fully implementing but there are a couple things that you can do is you can either pass an addition argument and upgrade the connection to a websocket that will bypass the rest of the middlewares. Or, what I do personally is just have any websocket connection go to a different end point. This will help with any future scalability issues. for example, if you need to create clusters of your server then you will have more control as well will help you testing your backend easier. That's what I would do atleast. My socket.io back end looks like this:

    server.ts

    oh yea I'm using typescript in the back end

    require('dotenv').config({ path: __dirname + '/.env' });
    import Koa from 'koa';
    const koa = new Koa();
    import cors from '@koa/cors';
    const PORT = process.env.CHAT_PORT || 3000;
    const ENV = process.env.NODE_ENV || 'development';
    const server = require('http').createServer(app, { origins: 'http://server.ip' });
    const io = (module.exports.io = require('socket.io')(server));
    import SocketManager from './lib/SocketManager';
    app.use(
      cors({
        origin: '*',
        optionsSuccessStatus: 200,
      }),
    );
    
    // server setup
    server.listen(PORT, (err: ErrorEvent): void => {
      if (err) console.error('❌ Unable to connect the server: ', err);
      console.log(`💻 Chat server listening on port ${PORT} - ${ENV} environment`);
    });
    
    io.on('connection', SocketManager);
    
    

    then just create a socket manager that imports the io instance and you can then go ahead and handle all the connections.

    I hope this is the answer you were looking for/gave you some better insight.