How do I authenticate Socket.io connections?
Use io.use() middleware: read the token from socket.handshake.auth.token, verify with jwt.verify(), find the user, and attach to socket.user. If verification fails, call next(new Error('Authentication failed')). The client passes the token in the auth option when connecting.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Setting Up Socket.io with Express in Node.js Server and Client Configuration
Create an HTTP server from the Express app (http.createServer(app)), initialize socketio with CORS config (socketio(server, { cors: { origin, credentials: true } })), add authentication middleware with io.use(), handle connection events with io.on('connection', ...), and listen on the HTTP server (not the Express app).
Install socket.io-client, import { io } from 'socket.io-client', connect with io(url, { withCredentials: true, auth: { token } }), listen with socket.on('event', callback), and emit with socket.emit('event', data). Clean up listeners in useEffect return with socket.off().
withCredentials: true allows the client to send cookies (including the JWT auth token) with cross-origin WebSocket connections. Without it, the auth middleware can't verify the user, and the connection will be rejected.
Still have questions?
Browse all our FAQs or reach out to our support team
