Initialize the Socket.IO Server
Now integrate Socket.IO into the Express application.
Create src/config/socket.js.
The Socket.IO Server class accepts the Node.js HTTP server as its first argument.
It also accepts configuration options, such as allowed origins, transport settings, and connection timeouts.
For our initial same-origin application, we do not need to enable additional cross-origin access.
CORS is an HTTP browser security mechanism. If your frontend and backend use different origins, configure the exact permitted origin instead of using wildcard access for authenticated applications.
import { Server } from 'socket.io';
export function initializeSocket(httpServer) {
const io = new Server(httpServer, {
cors: {
origin: false
}
});
return io;
}Creates a reusable function that initializes and returns the Socket.IO server. The application serves its frontend from the same origin, so no cross-origin browser access is required.
The Socket.IO Server class attaches real-time communication to an HTTP server.
Socket.IO configuration can be separated into its own module.
CORS configuration should match the frontend deployment architecture.