Registry / http-networking / socket.io-cookie-parser

socket.io-cookie-parser

JSON →
library1.0.0jsnpmunverified

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.

npm install socket.io-cookie-parser
INSTALL
IMPORT
SIG · SOCKET.IO-COOKIE-P
S
socket.io-cookie-parser
http-networkingjavascriptv1.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

cookieParser
const cookieParser = require('socket.io-cookie-parser');
import cookieParser from 'socket.io-cookie-parser';
This package primarily uses CommonJS `require()` syntax as shown in its documentation and examples. While it might be bundled or transpiled for ESM, its direct usage is CJS.
cookieParser (with options)
io.use(cookieParser('secret', { /* options */ }));
io.use(cookieParser({ /* options */ }, 'secret'));
Arguments for `cookieParser` directly mirror `express-cookie-parser`: the secret string comes first, followed by an options object. Misordering these is a common mistake.
socket.request.cookies
socket.request.cookies;
socket.cookies;
The parsed cookies are attached to the `request` object within the Socket.IO `socket` instance, not directly on the `socket` object itself. This aligns with Express's `req.cookies`.

This quickstart demonstrates how to integrate `socket.io-cookie-parser` into a Socket.IO server, showing how to parse both regular and signed cookies, and then utilize them within a Socket.IO authorization middleware.

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.'); });
Debug
Known issues
gotchaThe `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.
fix
Ensure `io.use(cookieParser(...))` is called early in your Socket.IO server setup, typically before any custom authorization or request handling middleware.
affects: >=1.0.0
gotchaWhen 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.
fix
Initialize the middleware with a secret: `io.use(cookieParser('your_secret_string'));`. This secret must match the one used to sign cookies on the client or HTTP server side.
affects: >=1.0.0
breakingWhile `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.
fix
Refer to the official `socket.io` migration guides for versions 3.x and 4.x to update your server setup. The core `io.use(cookieParser())` call should remain the same, but the `socketio(server)` initialization might change.
affects: >=1.0.0 (in conjunction with Socket.IO v3/v4)
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'cookies')
The `socket.io-cookie-parser` middleware has not been applied, or it has been applied after the code attempting to access `socket.request.cookies`.
fix
Ensure `io.use(cookieParser())` is called prior to any middleware or event listener that tries to access cookies from `socket.request`.
TypeError: cookieParser is not a function
This error typically occurs when trying to use ES module `import` syntax (`import cookieParser from 'socket.io-cookie-parser'`) without proper transpilation, or when using `require()` incorrectly.
fix
Use the CommonJS `require()` syntax as demonstrated in the package's documentation: `const cookieParser = require('socket.io-cookie-parser');`.
Upgrade
Version history
1.0.0latest on npm
Audit
Dependencies
cookie-parserrequiredThis package is a thin wrapper around express-cookie-parser, using its core parsing logic.
Agent activity
16 hits · last 30 days
node
12
OpenAI (training)
2
Resources
socket.io-cookie-parser — npm install socket.io-cookie-parser · libregistry