Koa Mount Middleware

4.2.0 · active · verified Wed Apr 22

koa-mount is a lightweight middleware package for the Koa web framework, designed to facilitate the mounting of other Koa applications or individual Koa middleware functions at specific URL paths. When a request matches a mounted path, koa-mount temporarily strips that path segment from the URL before passing the request downstream, allowing the mounted component to operate as if it were at the root of the application. This mechanism promotes modular application development by encapsulating sub-applications or middleware logic independently of their deployment path. The package is currently stable at version 4.2.0, with releases focusing on enhancements and bug fixes, indicating a mature and actively maintained status within the Koa ecosystem. It differentiates itself by providing a clear and efficient way to compose complex Koa applications from smaller, isolated parts.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to mount two separate Koa applications, 'a' and 'b', at distinct paths '/hello' and '/world' respectively, within a main Koa application. It illustrates `koa-mount`'s primary use case for creating modular web services where sub-applications handle specific route prefixes. Requests to '/hello' trigger app 'a', and '/world' trigger app 'b', while requests to the root '/' result in a 404.

import Koa from 'koa';
import mount from 'koa-mount';

// A small Koa application named 'a'
const a = new Koa();
a.use(async function (ctx, next){
  await next();
  ctx.body = 'Hello';
});

// Another small Koa application named 'b'
const b = new Koa();
b.use(async function (ctx, next){
  await next();
  ctx.body = 'World';
});

// The main Koa application
const app = new Koa();

// Mount 'a' at '/hello' and 'b' at '/world'
app.use(mount('/hello', a));
app.use(mount('/world', b));

app.listen(3000, () => {
  console.log('Koa app listening on port 3000');
  console.log('Try visiting:');
  console.log('  GET http://localhost:3000/hello');
  console.log('  GET http://localhost:3000/world');
  console.log('  GET http://localhost:3000/');
});

// To run this example:
// 1. Save as `app.mjs` (for ESM support)
// 2. npm install koa koa-mount
// 3. node app.mjs

view raw JSON →