Script Valley
WebSockets & Real-Time Applications
Socket.IO for Production Real-Time AppsLesson 4.5

How to use Socket.IO middleware for authentication

io.use middleware, socket.handshake.auth, next() function, error passing to next, socket.data for metadata, namespace-level middleware, middleware execution order

Authenticate Before connection Fires

Socket.IO middleware runs before the connection event. Use it to validate auth and attach user data:

const jwt = require('jsonwebtoken'); io.use((socket, next) => { const token = socket.handshake.auth.token; if (!token) { return next(new Error('Authentication required')); } try { const user = jwt.verify(token, process.env.JWT_SECRET); socket.data.user = user; // attach to socket for later use next(); } catch { next(new Error('Invalid token')); } }); io.on('connection', (socket) => { console.log('Authenticated user:', socket.data.user.id); });

Client Auth Configuration

Pass auth data from the Socket.IO client:

const socket = io('http://localhost:3000', { auth: { token: localStorage.getItem('jwt') } }); socket.on('connect_error', (err) => { if (err.message === 'Authentication required') { redirectToLogin(); } });

Middleware errors surface as connect_error events on the client with the error message. Always handle connect_error to give users actionable feedback. Use namespace-level middleware (on io.of('/admin').use(...)) to apply stricter rules to privileged namespaces.