Socket.IO Cookie Parser Middleware
raw JSON →socket.io-cookie-parser is a middleware specifically designed for Socket.IO applications, enabling the parsing of HTTP cookies on incoming WebSocket connections. Currently at stable version 1.0.0, this package acts as a thin wrapper around the widely used `express-cookie-parser` library, allowing developers to seamlessly share cookie-based session and authentication data between their Express.js HTTP server and Socket.IO real-time layer. Its primary utility lies in simplifying the process of accessing client-side cookies, making them available on `socket.request.cookies` and `socket.request.signedCookies`. This facilitates consistent authentication and state management in applications utilizing both traditional HTTP routes and WebSockets. The package is typically stable, following the lifecycle of its `express-cookie-parser` dependency, with new releases primarily addressing compatibility or minor enhancements.
Common errors
error TypeError: Cannot read properties of undefined (reading 'cookies') ↓
io.use(cookieParser()) is called prior to any middleware or event listener that tries to access cookies from socket.request. error TypeError: cookieParser is not a function ↓
require() syntax as demonstrated in the package's documentation: const cookieParser = require('socket.io-cookie-parser');. Warnings
gotcha The `socket.io-cookie-parser` middleware MUST be applied to the `io` instance using `io.use()` before any other middleware or authorization logic that intends to access `socket.request.cookies` or `socket.request.signedCookies`. Incorrect order will result in undefined cookie properties. ↓
gotcha When expecting signed cookies, a `secret` string *must* be provided to the `cookieParser` middleware. If no secret is provided, `socket.request.signedCookies` will be an empty object or undefined, even if signed cookies are present in the request headers. ↓
breaking While `socket.io-cookie-parser` itself has remained stable, significant API changes in `socket.io` versions 3 and 4 regarding server initialization and adapter configuration can indirectly affect how this middleware is set up if you are upgrading your `socket.io` dependency. ↓
Install
npm install socket.io-cookie-parser yarn add socket.io-cookie-parser pnpm add socket.io-cookie-parser Imports
- cookieParser wrong
import cookieParser from 'socket.io-cookie-parser';correctconst cookieParser = require('socket.io-cookie-parser'); - cookieParser (with options) wrong
io.use(cookieParser({ /* options */ }, 'secret'));correctio.use(cookieParser('secret', { /* options */ })); - socket.request.cookies wrong
socket.cookies;correctsocket.request.cookies;
Quickstart
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const cookieParser = require('socket.io-cookie-parser');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Use the cookie parser middleware
// 'keyboard cat' is a secret for signing cookies. Use a strong secret in production.
io.use(cookieParser('keyboard cat', {
decode: function (str) {
// Example custom decoding function, optional.
// Defaults to decodeURIComponent.
return str.replace(/%20/g, ' '); // Simple example, usually not needed.
}
}));
// Example authorization middleware using parsed cookies
io.use((socket, next) => {
const cookies = socket.request.cookies;
const signedCookies = socket.request.signedCookies;
console.log('Incoming connection. Raw headers:', socket.request.headers.cookie);
console.log('Parsed cookies:', cookies);
console.log('Parsed signed cookies:', signedCookies);
// A simple authorization check based on a signed cookie
if (signedCookies && signedCookies.auth_token === 'super_secret_token') {
console.log('Client authorized:', socket.id);
next(); // Authorize the connection
} else {
console.log('Client unauthorized:', socket.id);
next(new Error('Authentication required.')); // Reject the connection
}
});
io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}`);
socket.on('disconnect', () => {
console.log(`User disconnected: ${socket.id}`);
});
socket.emit('status', 'Welcome! Your session is active.');
});
app.get('/', (req, res) => {
res.send('<h1>Socket.IO with Cookie Parser</h1><p>Connect with a client to see cookie parsing in action.</p>');
});
server.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
console.log('Socket.IO listening for connections.');
});