Koa - Minimal, Expressive HTTP Middleware Framework for Node.js

repository·master·Indexed Apr 15, 2026

https://github.com/koajs/koa

Koa is a minimal, expressive HTTP middleware framework for Node.js that enables developers to build web applications and APIs with a stack-like middleware flow. It leverages async/await for clean control flow and delegates to Node's native HTTP objects via a Context object. Key features include middleware cascading, context extension via app.context, Async Local Storage support (v3+), and robust error handling through app.on('error') or try-catch blocks. Koa encourages composing middleware rather than including features out-of-the-box, offering a modern alternative to Express by eliminating callback hell. Routing is not included by default and requires third-party middleware.

Tokens
36.3K
Snippets
126
Records
242
Agent score
99%

What's inside koa

  1. Usage

    master

    Use ctx.set() or ctx.response.set() to manually set the Content-Disposition header with options.

    app.use(async (ctx) => {
      // Set attachment with custom filename
      ctx.set('Content-Disposition', 'attachment; filename="report.pdf"');
      ctx.body = fs.createReadStream('./report.pdf');
    });
  2. Manage Cookies with ctx.cookies

    master

    Access the ctx.cookies object to read and write signed or unsigned cookies. This property is a Cookies instance from the cookies package, configured with the application's keys and the request's secure state.

    Usage:

    // Read a cookie
    const userId = this.cookies.get('userId');
    
    // Set an unsigned cookie
    this.cookies.set('userId', '12345');
    
    // Set a signed cookie (requires app.keys to be set)
    this.cookies.set('userId', '12345', { signed: true });
    
    // Set a cookie with options
    this.cookies.set('userId', '12345', { 
      maxAge: 86400000, // 1 day
      httpOnly: true 
    });

    Configuration:

    • The keys option is automatically taken from this.app.keys.
    • The secure option is automatically taken from this.request.secure.

    You can also override the cookies instance by setting this.cookies directly, though this is rarely needed.

    Sources: lib/context.js

  3. Setup

    master

    Pass an array of secret keys to the app.keys property or the constructor options.

    const Koa = require('koa');
    const app = new Koa();
    
    // Configure signed cookie keys
    app.keys = ['secret', 'another-secret'];
    
    // Usage in middleware
    app.use(async (ctx, next) => {
      // Set a signed cookie
      ctx.cookies.set('name', 'tobi', { signed: true });
      
      // Access the signed cookie
      const name = ctx.cookies.get('name', { signed: true });
      
      await next;
    });
  4. Inspect Context Objects

    master

    The Context object supports inspection via ctx.inspect() and ctx.toJSON(), which return a JSON representation of the context. This is useful for debugging and logging.

    Usage:

    // Returns a JSON object
    const json = ctx.toJSON();
    console.log(json);
    // Output: {
    //   request: { ... },
    //   response: { ... },
    //   app: { ... },
    //   originalUrl: '/path',
    //   req: '<original node req>',
    //   res: '<original node res>',
    //   socket: '<original node socket>'
    // }
    
    // Can be used with console.log or util.inspect
    console.log(ctx);

    The inspect() method returns the same result as toJSON() for non-prototype instances.

    Sources: lib/context.js

  5. Update Dependencies: co and composition

    master

    Koa v2 removed internal dependencies that were previously bundled:

    • co: The co library is no longer bundled. You must require or import it directly if your code uses it.
    • composition: The composition library is no longer used and has been deprecated.

    Ensure you install co if you are using it in your application or middleware.

    const co = require('co')

    Sources: docs/migration-v1-to-v2.md

  6. Usage

    master

    You can access headers using any casing.

    app.use(async (ctx) => {
      // All of these will work:
      const auth = ctx.get('Authorization');
      const auth2 = ctx.get('authorization');
      const auth3 = ctx.get('AUTHORIZATION');
      
      ctx.body = auth;
    });
  7. Allow Valid Custom HTTP Status Codes

    master

    Koa's ctx.status setter now allows valid custom HTTP status codes beyond the standard set. This enables support for non-standard or experimental status codes if your application requires them.

    Usage:

    const Koa = require('koa');
    const app = new Koa();
    
    app.use(async (ctx) => {
      // Set a custom valid status code
      ctx.status = 418; // I'm a teapot
      ctx.body = 'I am a teapot';
    });

    Ensure the status code is a valid integer between 100 and 599.

    Sources: History.md

  8. Usage

    master

    Set the status code directly on the response object.

    app.use(async (ctx) => {
      ctx.status = 201; // Created
      ctx.body = { message: 'Resource created' };
    });
  9. Notes

    master
    • Buffer() with a number argument allocates uninitialized memory, which is a security risk.
    • Buffer.from() is the recommended way to create buffers from strings, arrays, or typed arrays.
    • Koa v2 internally uses Buffer.from() for all buffer operations.
    // Correct usage in Koa middleware
    app.use(async (ctx) => {
      const data = Buffer.from('Hello World', 'utf8');
      ctx.body = data.toString();
    });

    Sources: History.md

  10. Usage

    master

    No specific configuration is required. The framework handles this internally.

    app.use(async (ctx) => {
      // Koa will handle header sent state internally
      ctx.status = 200;
      ctx.body = 'OK';
    });