{"id":17950,"library":"socket.io-cookie-parser","title":"Socket.IO Cookie Parser Middleware","description":"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.","status":"maintenance","version":"1.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/mhuggins/socket.io-cookie-parser","tags":["javascript","socket.io","socket","cookie","cookies","cookie-parser","parse","parser","parsing"],"install":[{"cmd":"npm install socket.io-cookie-parser","lang":"bash","label":"npm"},{"cmd":"yarn add socket.io-cookie-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add socket.io-cookie-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is a thin wrapper around express-cookie-parser, using its core parsing logic.","package":"cookie-parser","optional":false}],"imports":[{"note":"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.","wrong":"import cookieParser from 'socket.io-cookie-parser';","symbol":"cookieParser","correct":"const cookieParser = require('socket.io-cookie-parser');"},{"note":"Arguments for `cookieParser` directly mirror `express-cookie-parser`: the secret string comes first, followed by an options object. Misordering these is a common mistake.","wrong":"io.use(cookieParser({ /* options */ }, 'secret'));","symbol":"cookieParser (with options)","correct":"io.use(cookieParser('secret', { /* options */ }));"},{"note":"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`.","wrong":"socket.cookies;","symbol":"socket.request.cookies","correct":"socket.request.cookies;"}],"quickstart":{"code":"const express = require('express');\nconst http = require('http');\nconst socketio = require('socket.io');\nconst cookieParser = require('socket.io-cookie-parser');\n\nconst app = express();\nconst server = http.createServer(app);\nconst io = socketio(server);\n\n// Use the cookie parser middleware\n// 'keyboard cat' is a secret for signing cookies. Use a strong secret in production.\nio.use(cookieParser('keyboard cat', {\n  decode: function (str) {\n    // Example custom decoding function, optional.\n    // Defaults to decodeURIComponent.\n    return str.replace(/%20/g, ' '); // Simple example, usually not needed.\n  }\n}));\n\n// Example authorization middleware using parsed cookies\nio.use((socket, next) => {\n  const cookies = socket.request.cookies;\n  const signedCookies = socket.request.signedCookies;\n\n  console.log('Incoming connection. Raw headers:', socket.request.headers.cookie);\n  console.log('Parsed cookies:', cookies);\n  console.log('Parsed signed cookies:', signedCookies);\n\n  // A simple authorization check based on a signed cookie\n  if (signedCookies && signedCookies.auth_token === 'super_secret_token') {\n    console.log('Client authorized:', socket.id);\n    next(); // Authorize the connection\n  } else {\n    console.log('Client unauthorized:', socket.id);\n    next(new Error('Authentication required.')); // Reject the connection\n  }\n});\n\nio.on('connection', (socket) => {\n  console.log(`User connected: ${socket.id}`);\n\n  socket.on('disconnect', () => {\n    console.log(`User disconnected: ${socket.id}`);\n  });\n\n  socket.emit('status', 'Welcome! Your session is active.');\n});\n\napp.get('/', (req, res) => {\n  res.send('<h1>Socket.IO with Cookie Parser</h1><p>Connect with a client to see cookie parsing in action.</p>');\n});\n\nserver.listen(3000, () => {\n  console.log('Server listening on http://localhost:3000');\n  console.log('Socket.IO listening for connections.');\n});","lang":"javascript","description":"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."},"warnings":[{"fix":"Ensure `io.use(cookieParser(...))` is called early in your Socket.IO server setup, typically before any custom authorization or request handling middleware.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=1.0.0 (in conjunction with Socket.IO v3/v4)"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure `io.use(cookieParser())` is called prior to any middleware or event listener that tries to access cookies from `socket.request`.","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`.","error":"TypeError: Cannot read properties of undefined (reading 'cookies')"},{"fix":"Use the CommonJS `require()` syntax as demonstrated in the package's documentation: `const cookieParser = require('socket.io-cookie-parser');`.","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.","error":"TypeError: cookieParser is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}