Let's we will host a socket.io + express server on cpanel's shared hosting. For this example I will host the server on mydomain.com/test22, so the folder is test22.
First of all setup the node.js app on cpanel
Please follow the image to setup a node.js app on cpanel hosting
As our main focus is not here to setup the node.js application on the shared hosting we will continue to focus on the socket.io setup both on the client and server side.
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
/** We will only modify the following path once,
and in other places e.g. on middlewares or whereever we need
will use the following constant */
const BASE_PATH = "/test22";
const io = socketIo(server, {
path: BASE_PATH,
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
/** Here in the following middleware express will handle
the subfolder's path for us */
app.use((req, res, next) => {
if (req.url.startsWith(BASE_PATH)) {
req.url = req.url.replace(BASE_PATH, "") || "/";
}
next();
});
/** Do whatever you need with socket **/
io.on("connection", (socket) => {
// ....
}
// API Route for Testing
app.get("/chat", (req, res) => {
res.json({ message: "Chat is running. Connect via WebSocket." });
});
// Start Server
const PORT = process.env.PORT || 5555;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
And on the client side:
// .env file
NEXT_PUBLIC_SOCKET_SERVER=http://mydomain.com
NEXT_PUBLIC_SUBFOLDER=test22
// in some kind of component
import { io } from "socket.io-client";
socketRef.current = io(process.env.NEXT_PUBLIC_SOCKET_SERVER, {
path: process.env.NEXT_PUBLIC_SUBFOLDER
});
// now do whatever you want with the socket connnection:
socketRef.current.emit('registerUser', { user: 1 }, response =>
{dispatch(newOnlineUser({ userId: response?.onlineUsers }));
});
Top comments (0)