5

I'm trying to utilize ws (web socket) in my Nextjs app.

Instead of creating a new server, I want to pass the current server object to the ws initialization:

const { Server } = require('ws');
wss = new Server({ myNextJs server instance here ... });

So: how to get a reference to the Nextjs server at run time?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Hairi
  • 3,318
  • 2
  • 29
  • 68
  • 2
    I found a way to make it work but IMHO hacky one https://gist.github.com/RadoslavMarinov/ec7efa8ae100ab3b4503163d0436e9a5 I took the idea from https://stackoverflow.com/a/62547135/5598574 – Hairi Mar 01 '21 at 15:51

2 Answers2

2

You can create a custom server. See https://nextjs.org/docs/advanced-features/custom-server

Here is an example:

const express = require("express");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const server = express();

app.prepare().then(() => {
    server.get("/some-random-path", (req, res) => res.send("Hello, world!"));
    server.get("*", (req, res) => handle(req, res));
    server.listen(3000, "0.0.0.0", () => {
        console.log("Application started on http://localhost:3000");
    });
});

Then just run your new server file

barbarbar338
  • 616
  • 5
  • 15
  • 2
    `Before deciding to use a custom server please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like serverless functions and Automatic Static Optimization.` Could it be achieved without loosing performance. There must be another way – Hairi Mar 01 '21 at 15:06
2

you can merge the code from my answer about socket.io

https://stackoverflow.com/a/62547135/2068876

with the example given on Github:

https://github.com/websockets/ws#multiple-servers-sharing-a-single-https-server

try something like this (not tested, but it seems valid since the principle is the same):

./pages/api/wss1.js

import { WebSocketServer } from "ws";

const wss1Handler = (req, res) => {
  if (!res.socket.server.wss1) {
    
    console.log("*First use, starting wss1");
    const wss1 = new WebSocketServer({ noServer: true });
    res.socket.server.on("upgrade", function upgrade(request, socket, head) {
      wss1.handleUpgrade(request, socket, head, function done(ws) {
        wss1.emit('connection', ws, request);
      });
    });
    res.socket.server.wss1 = wss1;
  } else {
    console.log("wss1 already running");
  }
  res.end();
}

export const config = {
  api: {
    bodyParser: false
  }
}

export default wss1Handler;

rogeriojlle
  • 1,046
  • 1
  • 11
  • 19