How to emit an event in Next.js 14 app router api #5236
-
How can I emit an event in app/router? then, when I create a message on app/api/comments/route.ts it work well if I leave socket variable is the instance I initialized in app/socket.ts
i also tried using socketHandler.getIO() but it always returns null, there is no IO on next's server to use directly |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hi! You need to handle it from your server: 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);
io.on("connection", (socket) => {
socket.on("comment", (comment) => {
socket.broadcast.emit("new-comment", comment); // to all connected clients except the sender
});
});
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
}); |
Beta Was this translation helpful? Give feedback.
Sorry for the delay! In that case, I think you need to store the
io
instance in the global scope: