Connect Socket.IO with Express
Import the Socket.IO initialization function into src/server.js.
Initialize Socket.IO using the HTTP server before starting the application.
The io instance will be used throughout the backend to emit events, manage rooms, and communicate with connected clients.
Updated src/server.js
import 'dotenv/config';
import express from 'express';
import { createServer } from 'node:http';
import { initializeSocket } from './config/socket.js';
const app = express();
app.use(express.json());
app.use(express.static('public'));
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
const httpServer = createServer(app);
const io = initializeSocket(httpServer);
httpServer.listen(process.env.PORT || 3000, () => {
console.log('HTTP and Socket.IO server started');
});The Express application and Socket.IO server now share the same HTTP server. The io variable represents the Socket.IO server instance.
Key Takeaways
Initialize Socket.IO before listening for incoming connections.
Keep the io instance accessible to event handlers.
Express and Socket.IO share one HTTP server.