I want to send real time notifications in my MERN app. And I am using socket.io for it. The thing I am confused with is that where should I initialize my socket.io if I want to use it on multiple routes. And how do I use it.
Every time a certain event happens I want to notify the user through a post route and there are multiple post routes like that. So my question is where should I initialize my socket.io for multiple usage and how should I use it. Please give me the code for it and make it clear for me.
Currently I am initializing my socket.io after connection of my server with my Database like this
mongoose
.connect(process.env.MongoDb_Url)
.then(() => {
const io = socket(
app.listen(5000, () => console.log("Server And Database Are Running")),
{
cors: {
origin: "http://localhost:3000",
},
}
);
io.on("connection", (socket) => {
socket.on("message", async (message) => {
const messageCreated = await chatModel.create({ ...message });
socket.emit("createdMessage", messageCreated);
});
});
})
.catch((error) => console.log(error.message));
Now what should I do ?
I actually achieved it through the app.set()
method in my app.js file
app.set("io",io)
and then you can just access that in the request object of your route.
console.log(req.app.settings.io)