Skip to content

How to emit an event in Next.js 14 app router api #5236

Answered by darrachequesne
yanghoxom asked this question in Q&A
Discussion options

You must be logged in to vote

Sorry for the delay! In that case, I think you need to store the io instance in the global scope:

// server.js
import { createServer } from "node:http";
import next from "next";
import { Server } from "socket.io";

const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();

app.prepare().then(() => {
  const httpServer = createServer(handler);

  const io = new Server(httpServer);

  globalThis.io = io;

  io.on("connection", (socket) => {
    // ...
  });

  httpServer
    .once("error", (err) => {

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@yanghoxom
Comment options

@yanghoxom
Comment options

@yanghoxom
Comment options

@darrachequesne
Comment options

Answer selected by yanghoxom
@yanghoxom
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants