node.jsexpresssocket.iocorslocaltunnel

localtunnel and CORS not working properly


I am using localtunnel to expose my backend and frontend. Right now, I have a very simple setup like this one:

const httpServer = require('http').createServer();
const socketIO = require('socket.io');

const io = socketIO(httpServer, { cors: { origin: '*' } });

io.on('connection', (socket) => {
  ...
});

httpServer.listen(5000, () => {
  console.log(`Listening on the port 5000`);
});

I then expose this backend with localtunnel with lt --port 5000. I then get the URL, set it up in my React frontend, start the frontend app running on port 3000 and then lt --port 3000. Then, when I try to connect to the backend, I keep getting this error.

Access to XMLHttpRequest at 'https://tame-mayfly-63.loca.lt/socket.io/?EIO=4&transport=polling&t=NbU6WbU' from origin 'https://spotty-robin-42.loca.lt' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

First I thought this was some error with localtunnel, but then tried with ngrok and the error is the same. I am enabling all origins from CORS, so I don't know what might be happening.

Doing curl "https://tame-mayfly-63.loca.lt/socket.io/?EIO=4&transport=polling" works, but I guess that's because CORS is ignored when making the request with cURL.


Solution

  • I found the solution for my problem. Looks like you first need to access to the dynamic url serving your backend and click on "Continue". After doing that, CORS won't be a problem anymore.