Tutorial of RESTful APIs with Express.js and TypeScript


This is a tutorial about how to build RESTful APIs with Express.js and TypeScript.

๐Ÿž Prepare Node env on macOS

If you donโ€™t have a development environment for Node.js, I recommend installing nvm. If you are interested, please see my post nvm: Node Version Manager .

๐Ÿฎ Install TypeScript

Before we get started, we should install TypeScript and TypeScript Node:

yarn global add typescript ts-node # npm install -g typescript ts-node

๐Ÿ€ Initiate a Project

Create a project folder and initiate the npm project.

# Create a folder and change directory to the folder
mkdir nodejs-api-project & cd nodejs-api-project

# Initiate npm configuration
yarn init # npm init

๐Ÿฏ Install Express

Install Express.js and dependencies.

yarn add @types/express express body-parser # npm install --save @types/express express body-parser

yarn add --dev nodemon typescript ts-node # npm install --save-dev nodemon typescript ts-node

๐Ÿšœ Configure TypeScript

Create tsconfig.json file.

{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"sourceMap": true,
"target": "es6",
"lib": ["dom", "esnext"],
"outDir": "./dist",
"baseUrl": "./src",
"alwaysStrict": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}

๐ŸŽณ Create source and dist folders

Create a folder to put TypeScript files. You will put your TypeScript files.

mkdir src

๐ŸŽ‰ Configure nodemon

Create nodemon.json file.

{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/server.ts"
}

๐Ÿš• Edit script configuration in package.json

Edit package.json file to add script configuration.

"scripts": {
"build": "tsc",
"dev": "nodemon -L",
"start": "node ./dist/server.js"
}

๐Ÿ—ฝ Create base Express code

Create src/app.ts file.

import * as express from "express";
import * as bodyParser from "body-parser";

class App {
public app: express.Application;

constructor() {
this.app = express();
this.config();
}

private config(): void {
// support application/json
this.app.use(bodyParser.json());
//support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
}
}

export default new App().app;

Additionally, generate src/server.ts.

import app from "./app";
const PORT = 3000;

app.listen(PORT, () => {
console.log("Express server listening on port " + PORT);
});

So, for your development, you can run a dev server by the following command:

yarn dev

express-typescript-start-bash

๐Ÿค” Create routing file

Create src/routes folder and add src/routes/MainRoutes.ts file.

import { Request, Response } from "express";

export class MainController {
public root(req: Request, res: Response) {
res.status(200).send({
message: "GET request successful!!"
});
}
}

export const mainController = new MainController();

After then, you should create src/controllers and add src/controllers/MainController.ts file.

import * as express from "express";
import { mainController } from "../controllers/MainController";

class MainRoutes {
public router: express.Router = express.Router();

constructor() {
this.config();
}

private config(): void {
this.router.get("/", (req: express.Request, res: express.Response) =>
mainController.root(req, res)
);
}
}

export const mainRoutes = new MainRoutes().router;

After creating the route file, we need to import it to src/app.ts:

import * as express from "express";
import * as bodyParser from "body-parser";
import { mainRoutes } from "./routes/MainRoutes";

class App {
public app: express.Application;

constructor() {
this.app = express();
this.config();
}

private config(): void {
// support application/json
this.app.use(bodyParser.json());
//support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
// Routing
this.app.use("/", mainRoutes);
}
}

export default new App().app;

Now you can see the result in Browser (http://localhost:3000).

localhost-result

๐Ÿ [Appendix] Dockerfile

This is Dockerfile for TypeScript & Express.js.

๐Ÿ˜ธ Development

FROM node

# Create app directory
RUN mkdir /app
WORKDIR /app

# Install app dependencies
COPY package.json ./
COPY yarn.lock ./

# Install libraries
RUN yarn && yarn global add typescript ts-node

# Bundle app source
COPY . .

# Build dist folder
RUN yarn build

EXPOSE 4000
CMD [ "yarn", "start" ]

๐Ÿˆ [Appendix] Basic Authentication

basic-auth-connect supports basic authentication in Express v4 apps.

Please run the following command:

Installation

yarn add basic-auth-connect

Configuration

Add following code:

import * as basicAuth from 'basic-auth-connect';

const app = express();
if (process.env.BASIC_AUTH_USER || process.env.BASIC_AUTH_PASSWORD) {
app.all(
"/*",
basicAuth(function(user, password) {
return (
user === process.env.BASIC_AUTH_USER &&
password === process.env.BASIC_AUTH_PASSWORD
);
})
);
}

After then, if you provide BASIC_AUTH_USER and BASIC_AUTH_PASSWORD environment variable, you can use basic authentication in Express app.

๐Ÿฎ References

๐Ÿ–ฅ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!