Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork3.2k
Expressive middleware for node.js using ES2017 async functions
License
koajs/koa
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.
Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. Thisincludes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.
Koa is not bundled with any middleware.
Koa requiresnode v18.0.0 or higher for ES2015 and async function support.
npm install koa
constKoa=require('koa');constapp=newKoa();// responseapp.use(ctx=>{ctx.body='Hello Koa';});app.listen(3000);
- Kick-Off-Koa - An intro to Koa via a set of self-guided workshops.
- Guide - Go straight to the docs.
Koa is a middleware framework that can take two different kinds of functions as middleware:
- async function
- common function
Here is an example of logger middleware with each of the different functions:
app.use(async(ctx,next)=>{conststart=Date.now();awaitnext();constms=Date.now()-start;console.log(`${ctx.method}${ctx.url} -${ms}ms`);});
// 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)=>{conststart=Date.now();returnnext().then(()=>{constms=Date.now()-start;console.log(`${ctx.method}${ctx.url} -${ms}ms`);});});
The middleware signature changed between v1.x and v2.x. The older signature is deprecated.
Old signature middleware support has been removed in v3
Please see theMigration Guide from v2.x to v3.x for information on upgrading from v2.x to v3.x, and theMigration Guide from v1.x to v2.x for information on upgrading from v1.x to v2.x.
Each middleware receives a KoaContext object that encapsulates an incominghttp message and the corresponding response to that message.ctx is often usedas the parameter name for the context object.
app.use(async(ctx,next)=>{awaitnext();});
Koa provides aRequest object as therequest property of theContext.Koa'sRequest object provides helpful methods for working withhttp requests which delegate to anIncomingMessagefrom the nodehttp module.
Here is an example of checking that a requesting client supports xml.
app.use(async(ctx,next)=>{ctx.assert(ctx.request.accepts('xml'),406);// equivalent to:// if (!ctx.request.accepts('xml')) ctx.throw(406);awaitnext();});
Koa provides aResponse object as theresponse property of theContext.Koa'sResponse object provides helpful methods for working withhttp responses which delegate to aServerResponse.
Koa's pattern of delegating to Node's request and response objects rather than extending themprovides a cleaner interface and reduces conflicts between different middleware and with Nodeitself as well as providing better support for stream handling. TheIncomingMessage can still bedirectly accessed as thereq property on theContext andServerResponse can be directlyaccessed as theres property on theContext.
Here is an example using Koa'sResponse object to stream a file as the response body.
app.use(async(ctx,next)=>{awaitnext();ctx.response.type='xml';ctx.response.body=fs.createReadStream('really_large.xml');});
TheContext object also provides shortcuts for methods on itsrequest andresponse. In the priorexamples,ctx.type can be used instead ofctx.response.type andctx.accepts can be usedinstead ofctx.request.accepts.
For more information onRequest,Response andContext, see theRequest API Reference,Response API Reference andContext API Reference.
The object created when executingnew Koa() is known as the Koa application object.
The application object is Koa's interface with node's http server and handles the registrationof middleware, dispatching to the middleware from http, default error handling, as well asconfiguration of the context, request and response objects.
Learn more about the application object in theApplication API Reference.
Check theTroubleshooting Guide orDebugging Koa inthe general Koa guide.
$ npm testTo report a security vulnerability, please do not open an issue, as this notifies attackers of the vulnerability. Instead, please emaildead_horse,jonathanong, andniftylettuce to disclose.
SeeAUTHORS.
- KoaJS Slack Group
- Badgeboard and list of official modules
- Examples
- Middleware list
- Wiki
- Reddit Community
- Mailing list
- 中文文档 v1.x
- 中文文档 v2.x
- #koajs on freenode
Looking for a career upgrade?
Support us with a monthly donation and help us continue our activities.
Become a sponsor and get your logo on our README on Github with a link to your site.
About
Expressive middleware for node.js using ES2017 async functions
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.



