Reputation: 3733
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?
Upvotes: 6
Views: 1490
Reputation: 1066
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;
Upvotes: 2
Reputation: 636
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
Upvotes: 2