How do I rate limit Socket.io events?
Use socket.use() middleware to check a rate limit map per user. Track event count and start time. If count exceeds the limit within the window, return next(new Error('Rate limit exceeded')). This prevents abuse like spamming messages.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Socket.io Authentication and Security JWT, CORS, and Best Practices
Use io.use() middleware: read the token from socket.handshake.auth.token, verify with jwt.verify(), find the user, and attach to socket.user. The client passes the token in the auth option: io(url, { auth: { token } }). Handle connect_error for auth failures.
Pass cors option when creating the server: socketio(server, { cors: { origin: process.env.CLIENT_URL, methods: ['GET', 'POST'], credentials: true } }). Use a specific origin (not '*'), and enable credentials for cookie-based auth. Never combine origin: '*' with credentials: true.
Before allowing a user to join a chat room, check if they are connected with the target user (ConnectionRequest with status 'accepted'). If not connected, reject with an error event. This prevents users from joining chats with people they're not connected to.
Still have questions?
Browse all our FAQs or reach out to our support team
