Socket.IO Cookie Parser Middleware

raw JSON →
1.0.0 verified Thu Apr 23 auth: no javascript maintenance

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.

error TypeError: Cannot read properties of undefined (reading 'cookies')
cause 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.
error TypeError: cookieParser is not a function
cause 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');.
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.
fix Ensure `io.use(cookieParser(...))` is called early in your Socket.IO server setup, typically before any custom authorization or request handling middleware.
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.
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.
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.
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.
npm install socket.io-cookie-parser
yarn add socket.io-cookie-parser
pnpm add socket.io-cookie-parser

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.');
});