Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
How to get a reference to the Nextjs server

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?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar

0

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;

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda