Replies: 1 comment 2 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.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
How can I emit an event in app/router?
right now, I need to use a custom server to init socket server based on the document https://socket.io/how-to/use-with-nextjs
then, when I create a message on app/api/comments/route.ts
I want to emit this event to all clients
but when I try to call
socket.emit('comment', newComment);
in app/api/comments/route.tsnothing happens, no error, no event emit
it work well if I leave
socket.emit
in frontend logic, but it doesn't match my expectation, i am looking for method that can emit event from nextjs backendsocket 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.
All reactions