I have a WebSocket API setup with a two-way communication integration using a lambda function to host the server. When I try running my published site, I get this error:
Access to XMLHttpRequest at 'https://z84fa4t7k2.execute-api.us-east-2.amazonaws.com/socket.io/?EIO=4&transport=polling&t=OzKEsbo' from origin 'https://NAMEOFWEBSITE.webflow.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
here’s the code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const awsServerlessExpress = require('aws-serverless-express');
const app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "https://NAMEOFWEBSITE.webflow.io/",
allowedHeaders: ["Access-Control-Allow-Origin"],
credentials: true
}
});
// Handle socket connections
io.on('connection', (socket) => {
console.log('A user connected');
socket.emit("hello", "world");
});
const serverExpress = awsServerlessExpress.createServer(app);
exports.handler = (event, context) => {
awsServerlessExpress.proxy(serverExpress, event, context);
};
And this is a code embed I have in Webflow:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var socket = io('wss://z84fa4t7k2.execute-api.us-east-2.amazonaws.com/ChatFunctionality/', {
withCredentials: true,
extraHeaders: {
"Access-Control-Allow-Origin": "*"
}
});
socket.on("hello", (arg) => {
console.log(arg);
});
});
</script>
Excuse the messy/possibly unnecessary code, I’ve been trying multiple things and asking chatgpt which isn’t always heplful but always confident lol.
Everyone’s solution seems to be adding this:
const io = socketIo(server, {
cors: {
origin: "*",
}
});
But this doesn’t work either, same error.
Is there a specific way I need to implement the socket with webflow?