- Install the necessary packages by running the following command in your terminal:
npm install socket.io next
- Create a new file called
server.js
in the root of your Next.js project and add the following code to it:
const { createServer } = require("http");
const { Server } = require("socket.io");
export default (req, res) => {
if (!res.socket.server.io) {
// This is the first time a client has connected to this server
const httpServer = createServer(req, res);
const io = new Server(httpServer, {
/ options /
});
res.socket.server.io = io;
io.on("connection", (socket) => {
console.log("a user connected");
socket.on("disconnect", () => {
console.log("user disconnected");
});
});
} else {
// If the server already has an instance of socket.io, use that
console.log("server.io already exists");
}
res.end();
};
- In your Next.js pages, you can now use the socket.io client to communicate with the server. For example:
import io from "socket.io-client";
const socket = io();
socket.on("connect", () => {
console.log("connected to server");
});
socket.on("disconnect", () => {
console.log("disconnected from server");
});
- You can now use the
socket
object to send and receive messages between the client and the server using socket.io.