How to Build a Back-end Server with Deno

By Rasyue | On May 22, 2020

In this tutorial, we are going to create a back-end server using Deno. Deno is a runtime for JavaScript and TypeScript that is based on the V8 JavaScript engine and the Rust programming language. It was created by Ryan Dahl, original creator of Node.js, and is focused on productivity. It was announced by Dahl in 2018 during his talk “10 Things I Regret About Node.js”.

Introduction

Now, if you are familiar with NodeJs and Express, you should already know how to run a server using NodeJs or Express. For example:

NodeJs

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Hello World!`);
});

Express

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

The above Express and NodeJs codes to run a server are pretty basic stuff that most people should already know by now.

Let’s look at how we are going to run a server using Deno.

Deno

Before that, let’s first install Deno on our machine, you may refer the installation guide here. Once you have Deno installed on your machine, open up your command line and run deno --version. If you have Deno installed correctly, then you should be seeing the version of the installed Deno.

command line showing version of deno
deno version

Now, create a new .ts file. This is one of the new stuff that Deno brings to the table, Deno is a secure runtime for both Javascript and Typescript, so you can use a Typescript file to write your code. Pretty neat huh?

Copy the below code to run a simple server.

 import { serve } from "https://deno.land/std/http/server.ts"

console.log("server is listening at 0.0.0.0:8000")
for await (const req of serve("0.0.0.0:8000")) {
	console.log(req.url)
  if (req.method === "GET") {
    req.respond({ body: 'Hello World!'})
  } 
}

Save the file with whatever name you like and in your command line. Run the following command, deno run your_file_name.ts. You should be seeing an error.

server-error

The return error is because Deno is secure by default. No file, network, or environment access, unless explicitly enabled. So, let’s go ahead and enable it. Run the following command deno run --allow-net your_file_name.ts

hello-world

Reno – Deno’s Module

There, now we have created a simple server using Deno. Now, let’s try to creates some routes using Reno (Deno’s module). Copy and paste the following into your .ts file.

import { listenAndServe, ServerRequest } from "https://deno.land/std@v0.51.0/http/server.ts";

import {
  createRouter,
  AugmentedRequest,
  createRouteMap,
  textResponse,
  jsonResponse,
} from "https://deno.land/x/reno@v1.0.0-alpha.1/reno/mod.ts";


export const routes = createRouteMap([
  ["/helloReno", () => textResponse("Response from Reno Server")],

  ["/swapi", async (req: AugmentedRequest) => {
    
    const res = await fetch(
      `https://swapi.dev/api/people`,
    );

    return jsonResponse(await res.json());
  }],

  
]);


const router = createRouter(routes);

(async () => {
  console.log("Listening for requests...");

  await listenAndServe(
    ":8001",
    async (req: ServerRequest) => {
      try {
        const res = await router(req);
        return req.respond(res);
      } catch (e) {
        return req.respond(e);
      }
    },
  );
})();

Now run the following, deno run --allow-net your_file_name.ts

reno-swapi

It is very simple to define your routes with Reno, I like how simple this module is but let’s take a look at another Deno’s module

Denotrain – Deno’s Module

Copy and paste the following into your typescript file and run it with deno run --allow-net your_file_name.ts

import { Application, Router, AppOptions } from "https://deno.land/x/denotrain@v0.4.4/mod.ts";

const options = {
    host : '127.0.0.1',
    port : 8080
}
const app = new Application(options);
const router = new Router();


app.use((ctx) => {});

app.get("/", (ctx) => {
 
  return {"Deno": "Train", "Hello" : "World"};
});

router.get("/addUser", async (ctx) => {
    return "This is the endpoint to add user!"; 
});
app.use("/user", router);



await app.run();

Using denotrain, we can setup our backend server similar to Express. Well to be fair, denotrain was inspired by Express by node.

JWT In Deno

Now, let’s try to create a JWT (JSON Web Token) in Deno. Using denotrain, we can do like so.

import { Application, Router, AppOptions } from "https://deno.land/x/denotrain@v0.4.4/mod.ts";
import { validateJwt } from "https://deno.land/x/djwt/validate.ts"
import {
  makeJwt,
  setExpiration,
  Jose,
  Payload,
} from "https://deno.land/x/djwt/create.ts"

const key = "rasyue-secret"
const payload: Payload = {
  iss: "rasyue",
  exp: setExpiration(new Date().getTime() + 60000),
}
const header: Jose = {
  alg: "HS256",
  typ: "JWT",
}

const options = {
    host : '127.0.0.1',
    port : 8080
}
const app = new Application(options);
const router = new Router();


app.use((ctx) => {});

app.get("/", (ctx) => {
  
  return {"Deno": "Train", "Hello" : "World", "jwt" : makeJwt({ header, payload, key })};
});

router.get("/addUser", async (ctx) => {
    return "This is the endpoint to add user!"; 
});
app.use("/user", router);



await app.run();

If you go to localhost:8080 you can see the JWT displaying on your page. It is as easy as you do it with Express.

There you have, some of the way you can create your back-end server with Deno. Stay tuned for more.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*