Deno nuggets: Oak — Redirect a user

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to redirect a user in Oak?

$ curl http://localhost:8000> GET / HTTP/1.1
< HTTP/1.1 302 Found
< location: /index
> GET /index HTTP/1.1
< HTTP/1.1 200 OK
< content-type: text/plain; charset=utf-8
< content-length: 10
Index page

Solution

There are two easy ways to redirect a user in Oak. The first way is by setting a redirect URL in the response attribute of the context object. The second way is by redirecting at the router level. Let’s look at both.

Redirect by setting context

The context.response object contains a method, called redirect, that can be used to set a redirect URL. The only input is the target URL string.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";const app = new Application();
const router = new Router();
router
.get("/", (ctx) => {
ctx.response.redirect("/index");
})
.get("/index", (ctx) => {
ctx.response.body = "Index page";
});
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });

Redirect at router level

The router level redirect is through redirect method provided by the router. The router level redirect API takes two inputs: from URL and target URL.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";const app = new Application();
const router = new Router();
router
.redirect("/", "/index")
.get("/index", (ctx) => {
ctx.response.body = "Index page";
});
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });

The behavior is the same in both cases.

$ curl http://localhost:8000 -L -v> GET / HTTP/1.1
< HTTP/1.1 302 Found
< location: /index
> GET /index HTTP/1.1
< HTTP/1.1 200 OK
< content-type: text/plain; charset=utf-8
< content-length: 10
Index page

--

--