How to create routes in Deno

In our base app tutorial we have seen how to create default page for our app. It is not a route, it’s middle-ware. In this example we create some basic routes using oak Router and add it as middle ware using the use method.

routes are the pages/links in a site, such as index page, about page, contact page etc

Create routes

We can create Oak router for our app in the same file. But as the application develop, the code become large, so in order to make it simple and easy to handle we keep routes in separate file and later include them as middle-ware to the main application.

In a folder called routes create a file route.ts

import { Router } from "";

const router = new Router()

router.get('/', (ctx) => {
  ctx.response.body = 'Home Page'
  ctx.response.status = 200

router.get('/about', (ctx) => {
  ctx.response.body = 'About Page'
  ctx.response.status = 200

router.get('/products', (ctx) => {
  ctx.response.body = 'Products Page'
  ctx.response.status = 200

export default router;

In the first line we import the Router from the Oak module, which is used to create our basic site routes. Then we export the router and will call the routers in the main.ts as follows.

Here ‘/’ route is the default page / index page of our app.

Arrow function

Every routes carry a function (ctx) =>, which is arrow function (feature of js and ts) having a context argument.

In bigger applications the functions are separated from routes and placed under folder controllers.

Each route can send message as response , also send a status code (which can be seen using developer tools) .

import { Application } from "";
import router from './routes/route.ts'
const app = new Application();

app.use((ctx) => {
    ctx.response.body = "Not found";

app.listen({ port: 8000 });
console.log('Server running on port 8000')

In the main.ts we added the route as middle ware, lets run the app with net permission.

deno run --allow-net main.ts

Now jump into the browser access your route

To stop the running server use Ctrl+C

All of my Deno projects will be published on my GitHub Repo, so keep watching.

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.