Mounting middleware for Koa.js applications that enables mounting apps and middleware at specific path prefixes
npx @tessl/cli install tessl/npm-koa-mount@4.2.00
# Koa Mount
1
2
Koa Mount provides mounting middleware for Koa.js applications that enables mounting entire Koa applications or individual middleware functions at specific path prefixes. It strips the mount path from the URL temporarily until the stack unwinds, allowing mounted apps and middleware to function correctly regardless of which path segments they operate on.
3
4
## Package Information
5
6
- **Package Name**: koa-mount
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install koa-mount`
10
11
## Core Imports
12
13
```javascript
14
const mount = require('koa-mount');
15
```
16
17
ES modules (if using a bundler that supports CommonJS imports):
18
19
```javascript
20
import mount from 'koa-mount';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const mount = require('koa-mount');
27
const Koa = require('koa');
28
29
// Create sub-applications
30
const blogApp = new Koa();
31
blogApp.use(async (ctx) => {
32
ctx.body = 'Blog content';
33
});
34
35
const apiApp = new Koa();
36
apiApp.use(async (ctx) => {
37
ctx.body = { message: 'API response' };
38
});
39
40
// Mount applications at different paths
41
const app = new Koa();
42
app.use(mount('/blog', blogApp));
43
app.use(mount('/api', apiApp));
44
45
app.listen(3000);
46
```
47
48
## Capabilities
49
50
### Mount Function
51
52
The primary export that mounts Koa applications or middleware at specified path prefixes.
53
54
```javascript { .api }
55
/**
56
* Mount app with prefix, app may be a Koa application or middleware function
57
* @param {String|Application|Function} prefix - Path prefix or app/middleware when path is omitted
58
* @param {Application|Function} [app] - Koa application, middleware function, or array of middleware
59
* @returns {Function} Koa middleware function
60
*/
61
function mount(prefix, app);
62
```
63
64
**Usage Patterns:**
65
66
1. **Mount at root path** (defaults to "/"):
67
```javascript
68
app.use(mount(koaApp));
69
```
70
71
2. **Mount application at specific path**:
72
```javascript
73
app.use(mount('/blog', blogApp));
74
```
75
76
3. **Mount middleware function**:
77
```javascript
78
app.use(mount('/api', async (ctx, next) => {
79
ctx.body = 'API endpoint';
80
await next();
81
}));
82
```
83
84
4. **Mount array of middleware**:
85
```javascript
86
app.use(mount('/admin', [
87
authMiddleware,
88
adminMiddleware
89
]));
90
```
91
92
5. **Cascading mounts** (nested mounting):
93
```javascript
94
const app = new Koa();
95
const blogApp = new Koa();
96
const adminApp = new Koa();
97
98
// Mount admin at /blog/admin
99
blogApp.use(mount('/admin', adminApp));
100
app.use(mount('/blog', blogApp));
101
102
// Request to /blog/admin/users will cascade through both mounts
103
```
104
105
### Path Matching Behavior
106
107
The mount function implements precise path matching rules:
108
109
- **Exact prefix matching**: `/prefix` matches `/prefix`, `/prefix/`, `/prefix/anything`
110
- **Trailing slash sensitivity**: `/prefix/` only matches paths with trailing slash after prefix
111
- **Word boundary protection**: `/prefix` does not match `/prefixother`
112
- **Path transformation**: Mount prefix is stripped from `ctx.path` during middleware execution
113
114
### Context Modifications
115
116
When mounting at non-root paths, the mount middleware modifies the Koa context:
117
118
```javascript { .api }
119
interface KoaContext {
120
/** Original request path, temporarily modified during mounted middleware execution */
121
path: string;
122
/** Set to the mount prefix path during execution (only when not mounting at "/") */
123
mountPath?: string;
124
}
125
```
126
127
**Example of path transformation**:
128
```javascript
129
// Request to "/blog/posts/123" with mount prefix "/blog"
130
// Inside mounted middleware: ctx.path becomes "/posts/123"
131
// ctx.mountPath is set to "/blog"
132
// After middleware completes: ctx.path restored to "/blog/posts/123"
133
```
134
135
### Error Handling
136
137
The mount function includes validation and proper error handling:
138
139
- **Path validation**: Mount path must start with "/" (throws assertion error if not)
140
- **Error propagation**: Errors in mounted middleware properly bubble up to parent application
141
- **Path restoration**: Context path is restored even when errors occur in mounted middleware
142
143
### Debugging Support
144
145
Built-in debugging capabilities using the `debug` module:
146
147
```bash
148
DEBUG=koa-mount node app.js
149
```
150
151
Debug output includes:
152
- Mount point registration
153
- Path matching and transformation events
154
- Enter/leave events during middleware execution
155
156
**Example debug output**:
157
```
158
koa-mount mount /blog blogApp +0ms
159
koa-mount enter /blog/posts -> /posts +1ms
160
koa-mount leave /blog/posts -> /posts +5ms
161
```
162
163
## Types
164
165
### Supported Application Types
166
167
```javascript { .api }
168
interface KoaApplication {
169
/** Array of middleware functions (used for mounting full applications) */
170
middleware: Function[];
171
/** Optional name for debugging purposes */
172
name?: string;
173
}
174
```
175
176
### Middleware Function Type
177
178
```javascript { .api }
179
/**
180
* Standard Koa middleware function signature
181
* @param {Object} ctx - Koa context object
182
* @param {Function} next - Next middleware function
183
*/
184
type MiddlewareFunction = (ctx: Object, next: Function) => Promise<void>;
185
```
186
187
### Dependencies
188
189
The mount function relies on these external dependencies:
190
191
- **debug**: Debug logging with namespace 'koa-mount'
192
- **koa-compose**: Composes middleware arrays into single middleware function
193
- **assert**: Node.js assertion module for path validation