Koa Cookie Parser Middleware

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

koa-cookie is a straightforward middleware for the Koa.js web framework, designed to parse HTTP `Cookie` headers and expose their contents as a convenient JavaScript object on `ctx.cookie`. Currently at version 1.0.0, this package provides a minimalist solution for accessing request cookies without additional features like cookie signing or complex serialization, adhering to a 'do one thing well' philosophy. Its release cadence is stable, with v1.0.0 being the primary and seemingly final release, indicating a maintenance-only status rather than active feature development. Key differentiators include its extreme simplicity and direct integration with Koa's context object, making it easy to drop into existing Koa applications, including those using `koa-router`. It's suitable for applications that handle cookie security (signing, encryption) at a different layer or don't require such features from the parser itself.

error TypeError: Cannot read properties of undefined (reading 'cookie')
cause The `koa-cookie` middleware was not applied or was applied after the code attempting to access `ctx.cookie`.
fix
Make sure app.use(cookie()); is called once at the start of your application's middleware chain.
error Cookies are not being parsed/found in ctx.cookie, even though they are present in the 'Cookie' header.
cause This is likely due to the `koa-cookie` middleware being placed incorrectly in the middleware chain, or a preceding middleware consuming/modifying the `Cookie` header before `koa-cookie` can process it.
fix
Verify that app.use(cookie()); is one of the first middleware applied to your Koa application. Inspect incoming headers with a debugging tool to ensure the 'Cookie' header is present as expected.
gotcha Middleware order is crucial. `koa-cookie` must be `app.use()`'d *before* any route handlers or other middleware that intend to access `ctx.cookie`, otherwise `ctx.cookie` will be undefined.
fix Ensure `app.use(cookie());` is called at the top of your middleware stack, before router or business logic middleware.
gotcha This package is a basic cookie parser and does *not* provide cookie signing, encryption, or other security features. Cookies parsed by `koa-cookie` are raw string values. For secure applications, consider using `koa-session` or similar solutions that handle signing and other security aspects.
fix Implement cookie signing/encryption separately (e.g., with `koa-session`, `koa-csrf`, or by manually using cryptographic libraries) or choose a more feature-rich session management library if these features are required.
deprecated The `koa-cookie` package appears to be unmaintained, with its last update occurring over 5 years ago. While it provides basic functionality, it might not be compatible with future Koa versions or address potential security vulnerabilities found in newer Node.js or browser environments.
fix For new projects or long-term stability, consider alternative, actively maintained cookie parsing or session management solutions for Koa. If using it, regularly test for compatibility and security issues.
npm install koa-cookie
yarn add koa-cookie
pnpm add koa-cookie

This quickstart demonstrates how to initialize `koa-cookie` middleware and access parsed cookies via `ctx.cookie` in a simple Koa application, along with an example of setting cookies (which `koa-cookie` does not handle directly).

import Koa from 'koa';
import cookie from 'koa-cookie';

const app = new Koa();

// Apply the cookie middleware
app.use(cookie());

// A simple route to demonstrate cookie access
app.use(async (ctx, next) => {
  if (ctx.path === '/') {
    const allCookies = ctx.cookie;
    console.log('Received cookies:', allCookies);
    
    // Example: access a specific cookie
    const userName = allCookies.name || 'Guest';
    ctx.body = `Hello, ${userName}! Your raw cookies: ${JSON.stringify(allCookies)}`;
  } else {
    await next();
  }
});

// Simulate setting a cookie (not part of koa-cookie itself)
app.use(async (ctx, next) => {
  if (ctx.path === '/set-cookie') {
    ctx.cookies.set('name', 'John Doe', { httpOnly: true, maxAge: 3600000 });
    ctx.cookies.set('session_id', 'abcd123xyz', { httpOnly: true, maxAge: 3600000 });
    ctx.body = 'Cookies set!';
  } else {
    await next();
  }
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on http://localhost:${port}`));