DEV Community

Moniruzzaman Saikat
Moniruzzaman Saikat

Posted on

1

How to run socket.io server on cpanel shared hosting even on subfolder ?

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

Image description

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}`));

Enter fullscreen mode Exit fullscreen mode

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 }));
});
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay