Home
Support Forums

Not working with my sockets server

Hi! I’m facing a problem here that I simply cannot debug and I didn’t find a solution elsewhere.
I have a simple socket server running standalone. Not related to netlify.


const express = require('express')
const app = express()

app.use(express.static('public'))
app.use(express.json())

const { createServer } = require('http');
const server = createServer(app)
require('dotenv').config()
const socket = require('socket.io')
const io = new socket.Server(server, {
    cors: {
        origin: '*',
        credentials: false,
    },
    pingTimeout: 10000
})

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

const port = process.env.PORT || 3333;

io.on('connection', (socket) => {
   
    socket.on('pedido_update', (objeto) => {
        socket.broadcast.emit(`pedido_${objeto.pedido_id}`)
    })

    socket.on('pedidos', (objeto) => {
        console.log(objeto);
        socket.broadcast.emit(`pedidos_${objeto.room}`)
    })

    socket.on('operation', (objeto) => {
        socket.broadcast.emit(`operation_${objeto.room}`)
    })
    
    socket.on("error", (error) => {
        console.log(error);
        if (error && error.message === "unauthorized event") {
            socket.disconnect();
        }
    });
});

server.listen(port, function () {
    console.log('Server listening.');
});

and I need that a netlify function emit an event to this server. something like this:

const {io} = require('socket.io-client')

module.exports.handler = async (event, context) => {
    const data = JSON.parse(event.body)
    const { SOME_ENV_VAR } = process.env
    context.callbackWaitsForEmptyEventLoop = false;

...blabla some logic...

        const socket = io(process.env.SOCKETS_URL);
        socket.emit('some_message', { room: DB_NAME })
        return {
            statusCode: 200,
            body: JSON.stringify({ response: some_response})
        };
    } catch (error) {
        return {
            statusCode: 500,
            body: 'Ocorreu um erro de processamento na operação e ela não foi concluída.'
        }
    }

}

on localhost (netlify dev) it works fine. All the logic works great and the event is sent the way it needs. When i go to production, the function just don’t even TOUCH the socket server. I have NO logs, NOTHING related to a response from there.

And YES I changed the URL to the same URL of the socket server.

It seems that the function is not going there. I need help, i’m so frustrated right now =(

ps. sorry about the poor english

My question is: What am I missing here? It is a header on the response? Why is it happening? I have another server communicating to this same socket server and all works fine. The problem begins when a Netlify function needs to communicate with it.

The answers to these other similar threads may assist:

I read this posts before posting this. They are not my case.
I guess there is a problem using socket.io-client on this situation, but what is killing me is that it is something with the netlify function, because it works in my other node server

I’ve not worked with socketio before so don’t know the particulars, but is the client that you’re using in the function only making rest based calls, or is it trying to communicate via websocket itself?

As the main piece of information I took from the threads I’d linked was:

Functions can’t “listen”

I don’t want the function to listen. It is just emitting an event to a standard node socket server, like you can see on the code. It works fine on local. This event message is not being sent on production.

What happens if you change that to just exports.handler?

Also, if that doesn’t change anything, mind telling us the site name?

i tried to change to exports.handler but I’m getting the same “result”
the site is just for test now, so the site name is “ql-bhdubyfssb-5de41093”

Oh, you seem to have many functions on that site. is the same thing happening in all or is it specific to just a few?

Just one function happening this. the “finish_purchase.js” one

I checked further, but there doesn’t seem to be anything obvious. Is it possible for you to share your repo?

I ended up resolving the problem by an alternative way. So that will not be necessary. But seems that, in some way, that socket.io-client package did not work well with serverless functions. I will consider this topic “solved” if it is ok

I just made my other node server to emit the messages I wanted. Since I have three parts communicating here. My netlify site, a socket server and other node server I just chose not to use the netlify part for this. but I guess it is not a fit for every kind of situation =/

1 Like

Thanks for confirming you found a workaround! While we recognize it is not the solution you hoped for, we appreciate you sharing it with the Forums.

1 Like