### Koa HTTP2 Server Setup
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Provides an example of configuring and starting an HTTP2 server with Koa using Node.js's `http2` module and a compatibility layer.
```javascript
import Koa from 'koa'
import http2 from 'node:http2'
import fs from 'node:fs'
const app = new Koa();
const onRequestHandler = app.callback();
const serverOptions = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}
const server = http2.createSecureServer(serverOptions, onRequestHandler);
server.listen(3000);
```
--------------------------------
### Koa.js Starter Templates and Boilerplates
Source: https://github.com/koajs/koa/wiki/Home
These projects offer pre-configured starting points for Koa.js applications, including common setups for controllers, routers, views, and API development.
```javascript
koa-starter: A simple Koajs application starter template that includes controller, router, and view
koa2-boilerplate: A minimal boilerplate of koa v2.
koa2-api-boilerplate: API-only (RESTful) boilerplate for Koa v2 with ES6-syntax & other.
koa2-starter-example: A starter for koa v2 with couchbase
koa-skeleton: Front end skeleton with koa backend
node-koajs-rest-skeleton: A simple Koajs 2.5 Application REST Skeleton (Koa v1.x & v2.x). Kubernetes-ready
koa2-kickstarter: An opinionated boilerplate for koa v2 with batteries included.
Pikachu: A Koa2 app boilerplate.
javascript-boilerplate: Node.js+Koa.js+PostgreSQL+React.js+Webpack+Mocha+Makefile, a starter kit for new apps.
```
--------------------------------
### Koa Server-Side Events with OpenAI
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
An example demonstrating how to implement server-side events (SSE) in Koa, specifically for streaming responses from OpenAI's chat completions API.
```javascript
import { PassThrough } from 'node:stream'
import OpenAI from 'openai'
import Koa from 'koa'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
const app = new Koa()
app.use(async (ctx, next) => { // TODO: use your favorite routing library
const { message } = await ctx.request.json() // this example uses koa-body-parsers
const stream = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: message }],
stream: true,
})
ctx.response.type = 'text/event-stream'
const body = ctx.body = new PassThrough()
// streaming needs to be handled in a separate event loop
;(async () => {
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content
if (!content) continue
body.write(`data: ${JSON.stringify({
delta: {
content: chunk.choices[0].delta.content || ''
}
})}\n\n`)
}
body.end()
})().catch((err) => app.emit('error', err))
})
app.listen(3000)
```
--------------------------------
### Install and Run Koa
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Installs Koa using npm and provides a basic command to run a Koa application. Requires Node.js v18.0.0 or higher.
```bash
$ nvm install 22
$ npm i koa
$ node my-koa-app.js
```
--------------------------------
### Install Koa
Source: https://github.com/koajs/koa/blob/master/Readme.md
Installs the Koa framework using npm. Requires Node.js v18.0.0 or higher.
```sh
npm install koa
```
--------------------------------
### Hello Koa Example
Source: https://github.com/koajs/koa/blob/master/Readme.md
A basic Koa application that listens on port 3000 and responds with 'Hello Koa' to all requests.
```javascript
const Koa = require('koa');
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000);
```
--------------------------------
### Koa Application Listening
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Shows the basic method for starting a Koa application to listen on a specified port.
```javascript
const Koa = require('koa');
const app = new Koa();
app.listen(3000);
```
--------------------------------
### Koa Async Operations with File System
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
An example of using async functions and promises in Koa to read filenames from a directory and process their contents in parallel. The combined content is then assigned to the response body.
```javascript
const fs = require('fs').promises;
app.use(async function (ctx, next) {
const paths = await fs.readdir('docs');
const files = await Promise.all(paths.map(path => fs.readFile(`docs/${path}`, 'utf8')));
ctx.type = 'markdown';
ctx.body = files.join('');
});
```
--------------------------------
### Async Middleware Example
Source: https://github.com/koajs/koa/blob/master/Readme.md
An example of Koa middleware using an async function to log request details and processing time. Requires Node.js v7.6+.
```javascript
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
```
--------------------------------
### Koa Response Time Middleware
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Example of a Koa middleware that calculates and sets the 'X-Response-Time' header for incoming requests. It uses async functions and manually calls `next()` to pass control to the downstream middleware.
```js
async function responseTime(ctx, next) {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
}
app.use(responseTime);
```
--------------------------------
### Koa Middleware Response Handling
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Demonstrates how middleware can control the response by omitting `next()`. This example shows two scenarios: one where all middleware executes, and another where downstream middleware is bypassed.
```javascript
app.use(async function (ctx, next) {
console.log('>> one');
await next();
console.log('<< one');
});
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
await next();
console.log('<< two');
});
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
});
```
```javascript
app.use(async function (ctx, next) {
console.log('>> one');
await next();
console.log('<< one');
});
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
console.log('<< two');
});
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
});
```
--------------------------------
### Common Function Middleware Example
Source: https://github.com/koajs/koa/blob/master/Readme.md
An example of Koa middleware using a common function to log request details and processing time. The `next()` function returns a Promise.
```javascript
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.
app.use((ctx, next) => {
const start = Date.now();
return next().then(() => {
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
```
--------------------------------
### Koa Logger Middleware with Options
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Demonstrates creating a Koa middleware factory that accepts options, such as a format string, to customize its behavior. The factory returns the actual middleware function.
```js
function logger(format) {
format = format || ':method "':url"';
return async function (ctx, next) {
const str = format
.replace(':method', ctx.method)
.replace(':url', ctx.url);
console.log(str);
await next();
};
}
app.use(logger());
app.use(logger(':method :url'));
```
--------------------------------
### koa-hello-world: Simple Koa 'Hello World' Middleware
Source: https://github.com/koajs/koa/wiki/Home
A basic Koa middleware that responds with 'Hello World'. It's primarily useful for testing Koa setups and ensuring the framework is running correctly.
```javascript
const helloWorld = require('koa-hello-world');
app.use(helloWorld());
```
--------------------------------
### Koa's Modularity and Third-Party Libraries
Source: https://github.com/koajs/koa/blob/master/docs/koa-vs-express.md
Explains Koa's barebones nature and reliance on third-party middleware for features like routing and body parsing, providing examples of common libraries.
```javascript
// Routing example using koa-router
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/', ctx => {
ctx.body = 'Hello from Koa Router!';
});
app.use(router.routes()).use(router.allowedMethods());
// Body parsing example using koa-bodyparser
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
// Security example using koa-helmet
const helmet = require('koa-helmet');
app.use(helmet());
app.listen(3000);
```
--------------------------------
### Upgrading Guide: Generator Middleware to Async
Source: https://github.com/koajs/koa/blob/master/docs/migration-v2-to-v3.md
Provides a direct comparison for upgrading Koa middleware from the old generator function style to the new async function style.
```javascript
// Old way (generator middleware)
app.use(function* (next) {
const start = Date.now()
yield next
const ms = Date.now() - start
console.log(`${this.method} ${this.url} - ${ms}ms`)
})
// New way (async middleware)
app.use(async (ctx, next) => {
const start = Date.now()
await next()
const ms = Date.now() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
```
--------------------------------
### Koa Middleware Signatures
Source: https://github.com/koajs/koa/blob/master/Readme.md
Explains the evolution of Koa middleware signatures, noting the removal of v1.x support in v3 and providing links to migration guides.
```APIDOC
Koa Middleware Signatures:
Koa v1.x Middleware Signature:
The middleware signature changed between v1.x and v2.x. The older signature is deprecated.
Koa v2.x and v3.x Middleware Signature:
- async function
- common function (returns a Promise)
Note: Old signature middleware support has been removed in v3.
Migration Guides:
- [Migration Guide from v2.x to v3.x](docs/migration-v2-to-v3.md)
- [Migration Guide from v1.x to v2.x](docs/migration-v1-to-v2.md)
```
--------------------------------
### Upgrading Guide: ctx.throw() Usage
Source: https://github.com/koajs/koa/blob/master/docs/migration-v2-to-v3.md
Details the updated usage of `ctx.throw()` for Koa v3.x, including throwing custom errors and using the `http-errors` package.
```javascript
// Old way (Koa v2.x)
ctx.throw(404, 'User not found', { user: 'john' });
// New way (Koa v3.x)
const error = new Error('User not found');
ctx.throw(404, error, { user: 'john' });
// You can also throw HTTP errors directly
const createError = require('http-errors');
ctx.throw(createError(404, 'User not found', { user: 'john' }));
```
--------------------------------
### Response Header Operations
Source: https://github.com/koajs/koa/blob/master/docs/api/response.md
Demonstrates how to get, check for, set, append, and remove response header fields. Includes examples for single and multiple header settings.
```APIDOC
response.get(field)
Get a response header field value with case-insensitive `field`.
Example:
const etag = ctx.response.get('ETag');
response.has(field)
Returns `true` if the header identified by name is currently set in the outgoing headers. The header name matching is case-insensitive.
Example:
const rateLimited = ctx.response.has('X-RateLimit-Limit');
response.set(field, value)
Set response header `field` to `value`.
Example:
ctx.set('Cache-Control', 'no-cache');
response.append(field, value)
Append additional header `field` with value `val`.
Example:
ctx.append('Link', '');
response.set(fields)
Set several response header `fields` with an object.
Example:
ctx.set({
'Etag': '1234',
'Last-Modified': date
});
This delegates to [setHeader](https://nodejs.org/dist/latest/docs/api/http.html#http_request_setheader_name_value) which sets or updates headers by specified keys and doesn't reset the entire header.
response.remove(field)
Remove header `field`.
```
--------------------------------
### Koa.js API Boilerplates and Frameworks Overview
Source: https://github.com/koajs/koa/wiki/Home
This section provides an overview of various projects that serve as boilerplates or starter kits for building RESTful APIs with Koa.js. These projects often include pre-configured setups for common functionalities like authentication, testing, and linting, utilizing modern JavaScript/TypeScript features.
```APIDOC
Project: Koa.js API Development
Description: A collection of projects providing a foundation for building RESTful APIs using the Koa.js framework. These projects often incorporate modern development practices and tools.
Key Features and Technologies:
- Koa.js (v2)
- ES2017+ / TypeScript
- RESTful API design
- User Authentication (JWT)
- CRUD operations
- Testing (Jest)
- Linting (ESLint)
- ORM/ODM (TypeORM, Camo.js)
- Validation (validate.js, koa-validate, class-validator)
- API Documentation (Swagger, ApiDoc)
- Dependency Injection (DI)
- AOP (Aspect-Oriented Programming)
- Docker / Kubernetes integration
Examples:
- koa-vue-notes-api: Full-stack SPA with Koa 2.3 backend and Vue 2.4 frontend, featuring user authentication and CRUD.
- koa2-es2017-api-boilerplate: Unopinionated Koa2 & ES2017+ boilerplate with Jest and ESLint.
- koa2-starter-kit: Koa2 starter kit using Camo.js ODM and validate.js.
- node-typescript-koa-rest: Koa2, TypeScript, logging, JWT, TypeORM, class-validator, Docker.
- koa-restful: TypeScript-based Koa 2 RESTful API library with DI, Swagger, Auth, AOP.
- aom: API Over Models - Koa@2 with TypeScript, TypeORM, ClassValidator.
```
--------------------------------
### Named Koa Middleware for Debugging
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Illustrates the practice of naming middleware functions, which is beneficial for debugging purposes in Koa applications.
```js
function logger(format) {
return async function logger(ctx, next) {
};
}
```
--------------------------------
### Koa Context Usage Example
Source: https://github.com/koajs/koa/blob/master/docs/api/context.md
Demonstrates how to access the Context object and its underlying request and response objects within Koa middleware.
```js
app.use(async ctx => {
ctx; // is the Context
ctx.request; // is a Koa Request
ctx.response; // is a Koa Response
});
```
--------------------------------
### Koa Debugging with NODE_DEBUG
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Shows how to use Node.js's built-in `util.debuglog` for debugging Koa applications by setting the `NODE_DEBUG` environment variable. This allows viewing Koa-specific logs during application boot.
```bash
$ NODE_DEBUG=koa* node --harmony examples/simple
```
--------------------------------
### Koa Documentation: Assert Example Correction
Source: https://github.com/koajs/koa/blob/master/History.md
Corrects an example in the documentation related to asserting responses for improved clarity. Addresses issue #1489.
```javascript
docs: fix assert example for response (#1489) (Imed Jaberi <>)
```
--------------------------------
### Koa Middleware Cascading Example
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Illustrates Koa's middleware cascading behavior, where middleware executes in a downstream and then upstream fashion. Includes logging and response time calculation.
```javascript
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
```
--------------------------------
### Composing Koa Middleware with koa-compose
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Shows how to combine multiple independent Koa middleware functions into a single middleware using the `koa-compose` library. This is useful for re-use and organization.
```js
const compose = require('koa-compose');
async function random(ctx, next) {
if ('/random' == ctx.path) {
ctx.body = Math.floor(Math.random() * 10);
} else {
await next();
}
};
async function backwards(ctx, next) {
if ('/backwards' == ctx.path) {
ctx.body = 'sdrawkcab';
} else {
await next();
}
}
async function pi(ctx, next) {
if ('/pi' == ctx.path) {
ctx.body = String(Math.PI);
} else {
await next();
}
}
const all = compose([random, backwards, pi]);
app.use(all);
```
--------------------------------
### Response Redirect Methods
Source: https://github.com/koajs/koa/blob/master/docs/api/response.md
Covers the `redirect()` and `back()` methods for performing HTTP redirects. Includes examples for setting status codes and bodies during redirection.
```APIDOC
response.redirect(url)
Perform a [302] redirect to `url`.
Example:
ctx.redirect('/login');
ctx.redirect('http://google.com');
To alter the default status of `302`, simply assign the status before or after this call. To alter the body, assign it after this call:
Example:
ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';
response.back(url)
Similar to `.redirect(url)`, but first checks the `referer` header to redirect. This is new in v3 as `.redirect(url, alt)` removes the special case `url = 'back'` option.
```
--------------------------------
### Koa Documentation Updates
Source: https://github.com/koajs/koa/blob/master/History.md
Documentation improvements for Koa, including updates to the guide, readme, and specific API sections like ctx.app.emit and response.set.
```APIDOC
docs: Document ctx.app.emit (#1284)
- Updates documentation to include details about ctx.app.emit.
docs: response.set(fields) won't overwrites previous header fields(#1282)
- Clarifies the behavior of response.set when dealing with header fields to prevent overwriting.
docs: update readme to add babel 7 instructions (#1274)
- Adds instructions for using Babel 7 within the Koa project's README.
docs: add table of contents for guide.md (#1267)
- Introduces a table of contents to the Koa guide for improved navigation.
docs: fix spelling in throw docs (#1269)
- Corrects spelling errors found in the documentation related to throwing errors.
doc: updated docs for throw() to pass status as first param. (#1268)
- Updates the documentation for the throw() method to specify that the status should be passed as the first parameter.
docs: Update error-handling.md (#1239)
- Provides updates to the error-handling documentation.
docs: Update koa-vs-express.md (#1230)
- Updates the comparison document between Koa and Express.
docs: better demonstrate middleware flow (#1195)
- Improves the explanation and demonstration of Koa's middleware flow.
docs: small grammatical fix in api docs index (#1111)
- Corrects minor grammatical errors in the API documentation index.
docs: fixed typo (#1112)
- Fixes a typo in the documentation.
docs: capitalize K in word koa (#1126)
- Ensures consistent capitalization of 'Koa' throughout the documentation.
```
--------------------------------
### Koa Middleware Naming for Debugging
Source: https://github.com/koajs/koa/blob/master/docs/guide.md
Explains how to set a middleware's name using `._name` property for better debugging output when the original function name is not available or controlled.
```javascript
const path = require('node:path');
const serve = require('koa-static');
const publicFiles = serve(path.join(__dirname, 'public'));
publicFiles._name = 'static /public';
app.use(publicFiles);
```
--------------------------------
### Converting Generators to Async Functions
Source: https://github.com/koajs/koa/blob/master/docs/migration-v1-to-v2.md
Provides an example of converting a Koa v1.x generator-style middleware to a Koa v2.x async function. This involves replacing `yield` with `await` and adjusting the function signature.
```js
app.use(async (ctx, next) => {
const user = await Users.getById(this.session.user_id);
await next();
ctx.body = { message: 'some message' };
})
```
--------------------------------
### Koaton Framework
Source: https://github.com/koajs/koa/wiki/Home
Koaton is a comprehensive and flexible framework for Koa, compatible with koa2. It's written in ES6/ES7 and includes a powerful router and ORM (CaminteJS). A CLI tool is available for project setup.
```javascript
/**
* Koaton: Complete and flexible framework for Koa (compatible with koa2).
* Written in ES6/ES7, features a world-class router and CaminteJS ORM.
* Includes a CLI Tool for project setup.
*/
// No specific code snippet provided, but the description implies its usage with Koa and its associated tools.
```
--------------------------------
### Koa Server Creation using http.createServer
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Explains that `app.listen()` is sugar for `http.createServer(app.callback()).listen()`, demonstrating the underlying mechanism.
```javascript
const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
```
--------------------------------
### Basic Koa Hello World Application
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
A minimal Koa application that responds with 'Hello World' to all requests. It demonstrates the basic structure of a Koa app using middleware.
```javascript
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
```
--------------------------------
### Koa Documentation: Onerror Example Correction
Source: https://github.com/koajs/koa/blob/master/History.md
Corrects an example in the documentation related to the `onerror` function for improved accuracy. Addresses issue #1459.
```javascript
docs: fixed incorrect onerror example (#1459) (Paul Annekov <>)
```
--------------------------------
### Running Tests
Source: https://github.com/koajs/koa/blob/master/Readme.md
The command to execute the test suite for the Koa project.
```bash
npm test
```
--------------------------------
### Koa Application Instantiation (v1.x)
Source: https://github.com/koajs/koa/blob/master/docs/migration-v1-to-v2.md
Shows the older way of instantiating a Koa application in v1.x, where the `new` keyword was optional.
```js
var koa = require('koa');
var app = module.exports = koa();
```
--------------------------------
### Koa Application Instantiation (v2.x)
Source: https://github.com/koajs/koa/blob/master/docs/migration-v1-to-v2.md
Demonstrates the correct way to instantiate a Koa application in v2.x using ES6 classes, which requires the `new` keyword.
```js
var koa = require('koa');
var app = module.exports = new koa();
```
--------------------------------
### Response Last-Modified and ETag Handling
Source: https://github.com/koajs/koa/blob/master/docs/api/response.md
Details how to get and set the `Last-Modified` header as a Date object and how to set the ETag header.
```APIDOC
response.lastModified
Return the `Last-Modified` header as a `Date`, if it exists.
response.lastModified=
Set the `Last-Modified` header as an appropriate UTC string. You can either set it as a `Date` or date string.
Example:
ctx.response.lastModified = new Date();
response.etag=
Set the ETag of a response including the wrapped `"`s. Note that there is no corresponding `response.etag` getter.
Example:
ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
```
--------------------------------
### Koa API Boilerplate
Source: https://github.com/koajs/koa/wiki/Home
An API application boilerplate project for Koa.js. It provides a starting point for building robust and scalable APIs with Koa.
```JavaScript
const Koa = require('koa');
const app = new Koa();
// API specific configurations and middleware setup
app.listen(3000);
```
--------------------------------
### Configuring Koa Application Settings
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Demonstrates how to set Koa application properties, such as 'proxy', either during instantiation or dynamically after creation.
```javascript
const Koa = require('koa');
const app = new Koa({ proxy: true });
```
```javascript
const Koa = require('koa');
const app = new Koa();
app.proxy = true;
```
--------------------------------
### Running Koa on Multiple Ports/Protocols
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Demonstrates how to use the `app.callback()` method with both HTTP and HTTPS servers to listen on different ports.
```javascript
const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);
```
--------------------------------
### AsyncLocalStorage Initialization and Usage
Source: https://github.com/koajs/koa/blob/master/docs/migration-v2-to-v3.md
Demonstrates how to enable and use `AsyncLocalStorage` in Koa v3 for context propagation, either by passing `true` or a custom instance during initialization.
```javascript
// Enable AsyncLocalStorage by passing true
const app = new Koa({ asyncLocalStorage: true })
app.use(async (ctx, next) => {
callSomeFunction()
await next()
})
function callSomeFunction() {
// Access the current context
const ctx = app.currentContext
// Do something with ctx
}
// Pass a custom AsyncLocalStorage instance
const { AsyncLocalStorage } = require('async_hooks')
const asyncLocalStorage = new AsyncLocalStorage()
const app = new Koa({ asyncLocalStorage })
app.use(async (ctx, next) => {
callSomeFunction()
await next()
})
function callSomeFunction() {
// Access the current context
const ctx = asyncLocalStorage.getStore()
// Do something with ctx
}
```
--------------------------------
### Koa Documentation: Babel Removal from README
Source: https://github.com/koajs/koa/blob/master/History.md
Removes references to Babel from the README file, streamlining the project's setup and dependencies. Addresses issue #1494.
```javascript
docs: remove babel from readme (#1494) (miwnwski <>)
```
--------------------------------
### Basic Middleware Usage
Source: https://github.com/koajs/koa/blob/master/Readme.md
Demonstrates the fundamental structure of Koa middleware, where each middleware function receives a context object and calls the next middleware in the stack.
```js
app.use(async (ctx, next) => { await next(); });
```
--------------------------------
### Koa2-React Boilerplate
Source: https://github.com/koajs/koa/wiki/Home
A boilerplate project for building Koa2 applications with a React frontend. It follows the MVC pattern and includes examples of essential features for web development.
```JavaScript
// Example of Koa2 server setup
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello Koa2!';
});
app.listen(3000);
```
--------------------------------
### Koa RBAC MongoDB Middleware
Source: https://github.com/koajs/koa/wiki/Home
Save the RBAC rules to MongoDB for dynamic RBAC setup and check. Enables persistent storage of RBAC configurations in MongoDB.
```javascript
import koaRbacMongo from 'koa-rbac-mongo';
import mongoose from 'mongoose';
// Assuming you have a Mongoose connection established
// mongoose.connect('mongodb://localhost:27017/rbac');
const rbacMongo = koaRbacMongo({
// MongoDB connection options or model configuration
});
app.use(rbacMongo);
```
--------------------------------
### Generator Middleware to Async/Await Conversion
Source: https://github.com/koajs/koa/blob/master/docs/migration-v2-to-v3.md
Demonstrates how to convert Koa middleware from using generator functions (with `koa-convert`) to modern async/await syntax.
```javascript
// Old way (using koa-convert with generator middleware)
const convert = require('koa-convert');
app.use(convert(function* (next) {
const data = yield fetchData();
yield next;
this.body = data;
}));
// New way (using async/await)
app.use(async (ctx, next) => {
const data = await fetchData();
await next();
ctx.body = data;
});
```
--------------------------------
### Koa Routing Middleware Overview
Source: https://github.com/koajs/koa/wiki/Home
This section lists various Koa middleware packages designed for routing. Each entry includes a brief description, a link to its repository, and its npm download count.
```javascript
kroute: Simple, self-contained koa routes and applications
koa-dispatch: Hybrid Koa router with multiple handlers and param support.
koa-barista: routing middleware based on the strong barista router.
koa-joi-router: Configurable, input and output validated routing for koa
koa-joi-controllers: Controller decorators for Koa using koa-joi-router
koa-version: Mounting app by version to different router.
koa-version-router: Automatic version for router.
koa-ovenware: Automatic Model / Controller Loader for Koa
koa-sub-domain: middleware to handle multilevel and wildcard subdomains
koa-forward-request: Forward request for koa.
impress-router: port Express router to koa
impress-router-table: Sails.js like routing for koa.js
koa-simple-router: Simple and fast REST routing middleware (koa 2.x ready)
koa-66: Router for koa v2
koa-react-router: koa 2 middleware for React server side rendering and routing with [react-router]
koa-dec-router: An ES6 decorator + class based router, support inherit, override, priority, auto load controllers, etc. Using [koa-router] under the hood.
koa-oai-router: Koa Router, based on OpenAPI, Swagger and Json Schema.
koa-minimal-router: Yet another minimal router for koa.
koa-router-find-my-way: Router middleware based on [find-my-way], a crazy fast http radix based router ([benchmark]).
koa-middleware-multiplexer: Multiplex Koa's middleware
```
--------------------------------
### koa-better-serve
Source: https://github.com/koajs/koa/wiki/Home
A small, simple, and correct middleware for serving files using koa-send.
```javascript
const koaBetterServe = require('koa-better-serve');
// Usage example:
// app.use(koaBetterServe(root, opts));
```
--------------------------------
### koa-file-server
Source: https://github.com/koajs/koa/wiki/Home
Static file serving middleware for Koa with additional features like etag and SPDY Push support.
```javascript
const koaFileServer = require('koa-file-server');
// Usage example:
// app.use(koaFileServer(root, opts));
```
--------------------------------
### Opinion - Koa Microframework
Source: https://github.com/koajs/koa/wiki/Home
Opinion is a microframework based on Koa, providing a minimal set of modules to help developers start building applications quickly. It focuses on simplicity and flexibility.
```JavaScript
const opinion = require('opinion');
const app = opinion();
// Add custom middleware and routes
app.listen(3000);
```
--------------------------------
### Koa Request Get Header
Source: https://github.com/koajs/koa/blob/master/docs/api/request.md
Retrieves the value of a specific request header, ignoring case sensitivity. This is useful for accessing headers like 'User-Agent', 'Content-Type', etc.
```APIDOC
request.get(field)
Return request header with case-insensitive `field`.
```
--------------------------------
### Koa's Promises and Async/Await Usage
Source: https://github.com/koajs/koa/blob/master/docs/koa-vs-express.md
Highlights Koa's core philosophy of using promises and async/await to manage asynchronous operations and simplify error handling, avoiding callback hell.
```javascript
// Example of Koa's promise-based control flow
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || 500;
ctx.body = err.message;
}
});
// Koa's context object abstracts Node's req/res
app.use(async ctx => {
ctx.body = 'Hello World!';
});
```
--------------------------------
### koa-spa
Source: https://github.com/koajs/koa/wiki/Home
Single page application server built upon koa-static-cache.
```javascript
const koaSpa = require('koa-spa');
// Usage example:
// app.use(koaSpa(root, opts));
```
--------------------------------
### Response Content-Type Management
Source: https://github.com/koajs/koa/blob/master/docs/api/response.md
Explains how to get and set the response's Content-Type. Covers setting via mime string, file extension, and handling default charset.
```APIDOC
response.type
Get response `Content-Type` void of parameters such as "charset".
Example:
const ct = ctx.type;
// => "image/png"
response.type=
Set response `Content-Type` via mime string or file extension.
Example:
ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';
Note: when appropriate a `charset` is selected for you, for example `response.type = 'html'` will default to "utf-8". If you need to overwrite `charset`, use `ctx.set('Content-Type', 'text/html')` to set response header field to value directly.
```
--------------------------------
### koa-webpack: Webpack Middleware for Koa2
Source: https://github.com/koajs/koa/wiki/Home
Development and Hot Module Replacement (HMR) middleware for Koa2. It simplifies the setup by composing webpack-dev-middleware and webpack-hot-middleware, providing efficient development builds.
```javascript
const koaWebpack = require('koa-webpack');
const webpackConfig = require('./webpack.config.js');
app.use(koaWebpack(webpackConfig));
```
--------------------------------
### koa-serve-list
Source: https://github.com/koajs/koa/wiki/Home
Serves directory listings for Koa, based on Express's serve-index.
```javascript
const koaServeList = require('koa-serve-list');
// Usage example:
// app.use(koaServeList(root, opts));
```
--------------------------------
### Koa Authentication Middleware Overview
Source: https://github.com/koajs/koa/wiki/Home
This section provides an overview of different authentication middleware available for Koa.js. It includes links to their respective repositories and download statistics.
```APIDOC
koa-basic-auth:
description: simple user/pass basic auth
supports_v2: true
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-basic-auth.png?style=flat-square"
koa-passport:
description: Passport middleware for Koa
supports_v2: true
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-passport.png?style=flat-square"
koa-jwt:
description: JWT (JSON Web Tokens) verification
supports_v2: true
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-jwt.png?style=flat-square"
koa-jwt-mongo:
description: Deal with JSON-web-token in mongodb
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-jwt-mongo.png?style=flat-square"
koa-user:
description: simple user module with tokens
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-user.png?style=flat-square"
koa-statelessauth:
description: custom validation based on `Authorization` header
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-statelessauth.png?style=flat-square"
koa-bearer-token:
description: Bearer token parser middleware for koa
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-bearer-token.png?style=flat-square"
koa-police:
description: Policy based authentication library for Koa
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-police.png?style=flat-square"
koa-weixin-token:
description: Weixin token services for koa
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-weixin-token.png?style=flat-square"
koa-http-auth:
description: simple HTTP auth, including Basic auth & Digest auth
supports_v2: false
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-http-auth.png?style=flat-square"
koa-cognito-middleware:
description: simple authentication with AWS Cognito user pools
supports_v2: true
npm_downloads_badge: "https://img.shields.io/npm/dm/koa-cognito-middleware.png?style=flat-square"
```
--------------------------------
### Koalerplate Boilerplate
Source: https://github.com/koajs/koa/wiki/Home
Koalerplate is a simple boilerplate for Koa 2, designed for building APIs using ES6 syntax. It provides a basic structure for starting new Koa API projects.
```javascript
/**
* Koalerplate: Simple Koa 2 boilerplate for APIs using ES6.
* Provides a starting point for building Koa-based APIs.
*/
// No specific code snippet provided, but the description implies its use as a project template.
```
--------------------------------
### Koa Router Middleware Overview
Source: https://github.com/koajs/koa/wiki/Home
This section provides an overview of various Koa router middleware packages. These packages offer different approaches to defining routes, handling parameters, and optimizing routing performance for Koa applications.
```APIDOC
koa-api-builder:
description: Build koa-router apis that are easier to maintain
supports_v2: true
koa-mapper:
description: A better router support params validation and OpenAPI generation.
supports_v2: true
koay-router:
description: Provide a faster router for Koa, and support configurable routes for Koa or express.
supports_v2: true
koa-architect:
description: Automates mounting and routing
supports_v2: true
koa-better-router:
description: Stable and lovely router for `koa`, using `path-match`. Foundation for building powerful, flexible and RESTful APIs easily.
supports_v2: true
koa-bestest-router:
description: Not complicated. No mutable state. Less than 100 lines of code.
supports_v2: true
koa-rest-router:
description: Most powerful, flexible and composable router for building enterprise RESTful APIs easily!
supports_v2: true
koa-route:
description: uber simple routing middleware
supports_v2: true
koa-routing:
description: routing middleware
supports_v2: false
koa2-router:
description: An express liked router middleware
supports_v2: true
koa2-routing:
description: Multiple files define route & Multiple front middlewares. Support redirect.
supports_v2: true
koa-router:
description: RESTful resource router (note: forked from ZijanHe/koa-router due to inactivity after being sold)
supports_v2: true
koa-radix-router:
description: Radix based routing, like `koa-router` but more faster
supports_v2: true
koa-directory-router:
description: Directory RESTful resource router
supports_v2: false
koa-frouter:
description: File as `path`
supports_v2: false
koa-tree-router:
description: high performance router for Koa
supports_v2: true
koa-trie-router:
description: Trie-based routing
supports_v2: true
koa-params:
description: Express style params support for koa-route.
supports_v2: false
```
--------------------------------
### Customize Request Context
Source: https://github.com/koajs/koa/blob/master/docs/api/index.md
Details how to extend the request context (`ctx`) by modifying `app.context`. This allows adding custom properties or methods to `ctx` that can be accessed across the application. For example, adding a database reference.
```js
app.context.db = db();
app.use(async ctx => {
console.log(ctx.db);
});
```
--------------------------------
### koa-static-resolver
Source: https://github.com/koajs/koa/wiki/Home
Koa static file resolver with features like directory handling, default index, path replacement, caching, live reload, and gzip.
```javascript
const koaStaticResolver = require('koa-static-resolver');
// Usage example:
// app.use(koaStaticResolver(opts));
```
--------------------------------
### Roo - Koa Boilerplate Reducer
Source: https://github.com/koajs/koa/wiki/Home
Roo is a thin layer on top of Koa designed to reduce initial boilerplate code for web applications. It helps developers jump-start their projects with less setup.
```JavaScript
const roo = require('roo');
const app = roo();
// Add custom routes and middleware
app.listen(3000);
```
--------------------------------
### koa-accept-webp
Source: https://github.com/koajs/koa/wiki/Home
Koa middleware for serving WebP images when support is detected.
```javascript
const koaAcceptWebp = require('koa-accept-webp');
// Usage example:
// app.use(koaAcceptWebp(opts));
```
--------------------------------
### Cottage - Simple Microframework
Source: https://github.com/koajs/koa/wiki/Home
Cottage is a simple and fast microframework built on Koa. It offers a lightweight foundation for developing web applications with minimal overhead.
```JavaScript
const Cottage = require('cottage');
const app = new Cottage();
// Define routes and middleware
app.listen(3000);
```
--------------------------------
### Using koa-convert for v1.x Middleware in v2.x
Source: https://github.com/koajs/koa/blob/master/docs/migration-v1-to-v2.md
Shows how to manually wrap Koa v1.x generator middleware using the `koa-convert` package to make it compatible with Koa v2.x. This is a temporary solution, and migrating to async functions is recommended.
```js
const convert = require('koa-convert');
app.use(convert(function *(next) {
const start = Date.now();
yield next;
const ms = Date.now() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
}));
```
--------------------------------
### Request Accept Header Check
Source: https://github.com/koajs/koa/blob/master/Readme.md
An example of using the Koa Context's Request object to check if the client accepts a specific content type (XML in this case). It uses `ctx.assert` for conditional error throwing.
```js
app.use(async (ctx, next) => {
ctx.assert(ctx.request.accepts('xml'), 406);
// equivalent to:
// if (!ctx.request.accepts('xml')) ctx.throw(406);
await next();
});
```
--------------------------------
### koa-favi
Source: https://github.com/koajs/koa/wiki/Home
Connect.favicon like middleware, defaults to using the Node logo.
```javascript
const koaFavi = require('koa-favi');
// Usage example:
// app.use(koaFavi());
```
--------------------------------
### koa2-request-middleware: Request Handling for Koa2
Source: https://github.com/koajs/koa/wiki/Home
A middleware for Koa2 designed to handle HTTP requests, specifically GET or POST requests for fetching or sending data. It simplifies common data retrieval and submission patterns.
```javascript
const requestMiddleware = require('koa2-request-middleware');
app.use(requestMiddleware());
```
--------------------------------
### koa-static-server
Source: https://github.com/koajs/koa/wiki/Home
Static file serving middleware for Koa with directory, rewrite, and index support.
```javascript
const koaStaticServer = require('koa-static-server');
// Usage example:
// app.use(koaStaticServer(opts));
```
--------------------------------
### koa-sendfile
Source: https://github.com/koajs/koa/wiki/Home
A barebone utility for sending files in Koa.
```javascript
const koaSendfile = require('koa-sendfile');
// Usage example:
// await koaSendfile(ctx, filePath);
```
--------------------------------
### Babel Register for Async Functions
Source: https://github.com/koajs/koa/wiki/Async-Functions-with-Babel
This snippet demonstrates how to use `babel-register` to transpile JavaScript code, enabling the use of async functions in Node.js versions prior to 7.6. It requires Babel to be installed and configured.
```js
require('babel-register');
// require the rest of the app that needs to be transpiled after the hook
const app = require('./app');
```
--------------------------------
### Stream Response Handling
Source: https://github.com/koajs/koa/blob/master/docs/api/response.md
Handles stream responses, automatically adding an error listener and destroying the stream on request closure. Provides an example of custom error handling without automatic stream destruction.
```js
const PassThrough = require('stream').PassThrough;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', (err) => ctx.onerror(err)).pipe(PassThrough());
});
```