ctx.redirect()
Sends a redirect response to the given URL with an optional status code (default 302).
Syntax
ctx.redirect(url, [alt]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
url | string | Yes | The URL to redirect to. Use `"back"` to redirect to the `Referer` header value. |
alt | string | No | Fallback URL used when `url` is `"back"` and there is no `Referer` header. Defaults to `"/"`. |
Returns
void — Returns nothing; sets status, Location header, and a short HTML body.
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
if (ctx.path === '/old') {
ctx.redirect('/new', '/');
} else if (ctx.path === '/login') {
// after login, go back to previous page
ctx.redirect('back', '/dashboard');
} else {
ctx.body = 'Current page';
}
});
app.listen(3000);
Output
GET /old → 302 Location: /new
GET /login → 302 Location: (Referer or /dashboard)
// Permanent redirect with 301
ctx.status = 301;
ctx.redirect('https://new.example.com/');
Output
HTTP/1.1 301 Moved Permanently
Location: https://new.example.com/
Notes
`ctx.redirect()` automatically sets a `text/html` body with a link for
clients that don't follow redirects. Assign `ctx.status` before calling
`ctx.redirect()` if you want a status other than `302`.