DEV Community

suin
suin

Posted on

How to redirect in Koa with TypeScript

This post explains how to redirect in Koa with TypeScript.

How to redirect in Koa

The redirect() method is available in the ctx object. So to redirect, just call it.

ctx.redirect(url)
Enter fullscreen mode Exit fullscreen mode

Full example of ctx.redirect

import Koa from "koa";
import _ from "koa-route";

const app = new Koa()
app.use(_.get('/old', async ctx => {
    ctx.redirect('/new')
}))
app.use(_.get('/new', async ctx => {
    ctx.body = 'redirected!'
}))

app.listen(4000)
Enter fullscreen mode Exit fullscreen mode

When you send a request to the path /old, the server will respond to 302 status. Also, the Location header value will be the URL that was passed to the redirect method.

HTTP/1.1 302 Found
Connection: keep-alive
Content-Length: 39
Content-Type: text/html; charset=utf-8
Date: Mon, 02 Sep 2019 06:01:51 GMT
Location: /new

Redirecting to <a href="/new">/new</a>.
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)