websocketsocket.ioiis-10nextjs14

Deploying NextJS with Socket.IO application in IIS 10


I already deployed my application in IIS using the tutorial of Halfblood Programmer. I am using HttpPlatformHandler v1.2, the application is already running but the problem is the websocket. Socket.io pooling is not found, returning 404. I already enabled and installed the IIS WebSocket Protocol support, added <webSocket enabled="true" /> in my web.config but nothing works. Please help me. Btw, my application is running on windows server 2022 and iis 10

    //server.js
    const { createServer } = require('http');
    const { parse } = require('url');
    const next = require('next');
    const { Server } = require('socket.io');
    
    const dev = process.env.NODE_ENV !== 'production';
    const app = next({ dev });
    const handle = app.getRequestHandler();
    
    app.prepare().then(() => {
        const server = createServer((req, res) => {
            const parsedUrl = parse(req.url, true);
            handle(req, res, parsedUrl);
        });
    
        const io = new Server(server, {
            cors: {
            origin: 'http://ipaddress:3001', // Update this to the origin you want to allow
            methods: ['GET', 'POST']
            }
        });
    
        io.on('connection', (socket) => {
            console.log('Client connected:', socket.id);
    
            socket.on('register', (userId) => {
            // Handle user registration
            });
    
            socket.on('send_message', ({ itemId, message, senderId, origin }) => {
                io.emit('new_message', { itemId, message, senderId, origin });
            });
    
            socket.on('disconnect', () => {
            console.log('Client disconnected:', socket.id);
            // Handle user disconnection
            });
        });
    
        server.listen(3001, (err) => {
            if (err) throw err;
            console.log('> Ready on http://ipaddress:3001');
        });
    });

    ---package.json
    "scripts": {
        "dev": "node server.js",
        "build": "next build",
        "start": "NODE_ENV=production node server.js",
        "lint": "next lint"
      }

enter image description here


Solution

  • You made a typical mistake to hook your server to a dedicated port number (3001).

    Like I showed in all related posts, such as this one, you have to let IIS decide which port to use.

            const port = process.env.PORT || 3001;
            server.listen(port, (err) => {
                if (err) throw err;
                console.log(`> Ready on http://ipaddress:${port}`);
            });
    

    Note that you have to edit other locations where you hard coded port number.