ctx.attachment()
Sets the `Content-Disposition` header to `attachment` so the browser prompts a file download instead of rendering the response.
Syntax
ctx.attachment([filename]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
filename | string | No | The suggested filename for the download. When provided, also sets the `Content-Type` based on the file extension. |
Returns
void — Returns nothing.
Examples
import Koa from 'koa';
import { createReadStream } from 'node:fs';
const app = new Koa();
app.use(async (ctx) => {
if (ctx.path === '/download') {
ctx.attachment('report-2026.pdf');
ctx.body = createReadStream('./report.pdf');
}
});
app.listen(3000);
Output
Content-Disposition: attachment; filename="report-2026.pdf"
Content-Type: application/pdf
Notes
Relies on the [content-disposition](https://github.com/jshttp/content-disposition)
package which handles RFC 6266 encoding for non-ASCII filenames. Set
`ctx.type` explicitly if you need a different Content-Type than what is
inferred from the filename extension.