DEV Community

suin
suin

Posted on

3 1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs