ctx.response.type
Gets or sets the `Content-Type` response header using MIME types or file extensions.
Syntax
ctx.response.type = type // or ctx.type = type Parameters
| Name | Type | Required | Description |
|---|---|---|---|
type | string | Yes | A MIME type string (`"application/json"`) or a file extension without the dot (`"json"`, `"html"`, `"png"`). Koa resolves the extension to a MIME type via the `mime-types` package. |
Returns
string — The current Content-Type without parameters (e.g. `"application/json"`).
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
ctx.type = 'html';
ctx.body = '<h1>Hello Koa</h1>';
});
app.listen(3000);
Output
Content-Type: text/html; charset=utf-8
app.use(async (ctx) => {
ctx.type = 'application/pdf';
ctx.body = pdfBuffer;
});
Output
Content-Type: application/pdf
Notes
When you assign an object or array to `ctx.body`, Koa automatically sets
`Content-Type` to `application/json`. For strings it defaults to
`text/html` if the string contains a `<` character, otherwise
`text/plain`. Manually setting `ctx.type` overrides the inferred type.