How to Use Socket.io with Express: Simple Setup Guide
To use
socket.io with express, create an Express app and then attach a socket.io server to the HTTP server created from Express. This allows real-time communication alongside your Express routes using WebSockets.Syntax
First, create an Express app and an HTTP server from it. Then, initialize socket.io by passing the HTTP server. Use io.on('connection') to listen for new client connections and handle events.
express(): creates the Express app.http.createServer(app): creates an HTTP server from Express.new Server(httpServer): creates a Socket.io server attached to HTTP.io.on('connection', callback): listens for client connections.
javascript
import express from 'express'; import { createServer } from 'http'; import { Server } from 'socket.io'; const app = express(); const httpServer = createServer(app); const io = new Server(httpServer); io.on('connection', (socket) => { console.log('A user connected'); socket.on('disconnect', () => { console.log('User disconnected'); }); }); httpServer.listen(3000, () => { console.log('Server listening on port 3000'); });
Example
This example shows a complete Express server with Socket.io that logs when users connect or disconnect. It also serves a simple HTML page that connects to the Socket.io server and displays connection status.
javascript
import express from 'express'; import { createServer } from 'http'; import { Server } from 'socket.io'; const app = express(); const httpServer = createServer(app); const io = new Server(httpServer); app.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Socket.io Test</title></head> <body> <h1>Socket.io with Express</h1> <p id="status">Connecting...</p> <script src="/socket.io/socket.io.js"></script> <script> const socket = io(); socket.on('connect', () => { document.getElementById('status').textContent = 'Connected with ID: ' + socket.id; }); socket.on('disconnect', () => { document.getElementById('status').textContent = 'Disconnected'; }); </script> </body> </html> `); }); io.on('connection', (socket) => { console.log('User connected:', socket.id); socket.on('disconnect', () => { console.log('User disconnected:', socket.id); }); }); httpServer.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
User connected: <socket_id>
User disconnected: <socket_id>
Common Pitfalls
Common mistakes include:
- Trying to attach
socket.iodirectly to the Express app instead of the HTTP server. - Not creating the HTTP server explicitly, which is required for Socket.io to work.
- Forgetting to serve the client-side
/socket.io/socket.io.jsscript, causing client connection failures. - Not handling CORS properly if client and server run on different origins.
Always use the HTTP server from Express to initialize Socket.io.
javascript
/* Wrong way: attaching socket.io to express app directly (does NOT work) */ import express from 'express'; import { Server } from 'socket.io'; const app = express(); const io = new Server(app); // ❌ This is incorrect /* Right way: attach socket.io to HTTP server */ import { createServer } from 'http'; const httpServer = createServer(app); const ioCorrect = new Server(httpServer); // ✅ Correct httpServer.listen(3000);
Quick Reference
- Use
createServer(app)to get HTTP server from Express. - Pass HTTP server to
new Server(httpServer)for Socket.io. - Listen for
'connection'event to handle clients. - Serve client script from
/socket.io/socket.io.js. - Handle CORS if needed with Socket.io options.
Key Takeaways
Attach Socket.io to the HTTP server created from Express, not directly to the Express app.
Use io.on('connection') to handle new client connections and events.
Serve the Socket.io client script from /socket.io/socket.io.js for browser clients.
Remember to handle CORS if your client and server are on different origins.
Always start the HTTP server with httpServer.listen() to enable Socket.io communication.