Type something to search...
Setting up Node JS, Express,  Prettier, ESLint and Husky Application with Babel and Typescript: Part 1

Setting up Node JS, Express, Prettier, ESLint and Husky Application with Babel and Typescript: Part 1

Introduction

All code from this tutorial as a complete package is available in this repository. If you find this tutorial helpful, please share it with your friends and colleagues, and make sure to star the repository.

So, in this little tutorial, I’ll explain how to set up babel for a basic NodeJS Express, and typescript application so that we may utilize the most recent ES6 syntax in it.

What is TypeScript?

TypeScript is a superset of JavaScript that mainly offers classes, interfaces, and optional static typing. The ability to enable IDEs to give a richer environment for seeing typical mistakes as you enter the code is one of the major advantages.

  • JavaScript and More: TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor.
  • A Result You Can Trust: TypeScript code converts to JavaScript, which runs anywhere JavaScript runs: In a browser, on Node.js or Deno and in your apps.
  • Safety at Scale: TypeScript understands JavaScript and uses type inference to give you great tooling without additional code.

What is Babel?

Babel Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

  • Transform syntax
  • Polyfill features that are missing in your target environment (through a third-party polyfill such as core-js)
  • Source code transformations (codemods)

Project Setup

We’ll begin by creating a new directory called template-express-typescript-blueprint and then we’ll create a new package.json file. We’re going to be using yarn for this example, but you could just as easily use NPM if you choose, but yarn is a lot more convenient.

Terminal window
mkdir template-express-typescript-blueprint
cd template-express-typescript-blueprint
yarn init -y

Now we’ll connect to our new project with git.

Terminal window
git init

A new Git repository is created with the git init command. It may be used to start a fresh, empty repository or convert an existing, unversioned project to a Git repository. This is often the first command you’ll perform in a new project because the majority of additional Git commands are not accessible outside of an initialized repository.

Now we’ll connect to our new project with github, creating a new empty repository, after we’ve created a new directory called template-express-typescript-blueprint.

Terminal window
echo "# Setting up Node JS, Express, Prettier, ESLint and Husky Application with Babel and Typescript: Part 1" >> README.md
git init
git add README.md
git commit -m "ci: initial commit"
git branch -M main
git remote add origin git@github.com:<YOUR_USERNAME>/template-express-typescript-blueprint.git
git push -u origin main

Engine Locking

The same Node engine and package management that we use should be available to all developers working on this project. We create two new files in order to achieve that:

  • .nvmrc: Will disclose to other project users the Node version that is being utilized.
  • .npmrc: reveals to other project users the package manager being used.

.nvmrc is a file that is used to specify the Node version that is being used.

Terminal window
touch .nvmrc

.nvmrc

1
lts/fermium

.npmrc is a file that is used to specify the package manager that is being used.

Terminal window
touch .npmrc

.npmrc

1
engine-strict=true
2
save-exact = true
3
tag-version-prefix=""
4
strict-peer-dependencies = false
5
auto-install-peers = true
6
lockfile = true

Now we’ll add few things to our package.json file.

package.json

1
{
2
"name": "template-express-typescript-blueprint",
3
"version": "0.0.0",
4
"description": "",
5
"keywords": [],
6
"main": "index.js",
7
"license": "MIT",
8
"author": {
9
"name": "Mohammad Abu Mattar",
10
"email": "mohammad.abumattar@outlook.com",
11
"url": "https://mkabumattar.github.io/"
12
},
13
"homepage": "https://github.com/MKAbuMattar/template-express-typescript-blueprint#readme",
14
"repository": {
15
"type": "git",
16
"url": "git+https://github.com/MKAbuMattar/template-express-typescript-blueprint.git"
17
},
18
"bugs": {
19
"url": "https://github.com/MKAbuMattar/template-express-typescript-blueprint/issues"
20
}
21
}

Notably, the usage of engine-strict said nothing about yarn in particular; we handle that in packages.json:

open packages.json add the engines:

1
{
2
...,
3
"engines": {
4
"node": ">=14.0.0",
5
"yarn": ">=1.20.0",
6
"npm": "please-use-yarn"
7
}
8
}

Installing and Configuring TypeScript

TypeScript is available as a package in the yarn registry. We can install it with the following command to install it as a dev dependency:

Terminal window
yarn add -D typescript @types/node

Now that TypeScript is installed in your project, we can initialize the configuration file with the following command:

Terminal window
yarn tsc --init

Now we can start config the typescript configuration file.

tsconfig.json

1
{
2
"compilerOptions": {
3
"target": "es2016",
4
"module": "commonjs",
5
"rootDir": "./src",
6
"moduleResolution": "node",
7
"baseUrl": "./src",
8
"declaration": true,
9
"emitDeclarationOnly": true,
10
"outDir": "./build",
11
"esModuleInterop": true,
12
"forceConsistentCasingInFileNames": true,
13
"strict": true,
14
"skipLibCheck": true
15
}
16
}

Installing and Configuring Babel

In order to set up babel in the project, we must first install three main packages.

  • babel-core: The primary package for running any babel setup or configuration is babel-core.
  • babel-node: Any version of ES may be converted to ordinary JavaScript using the babel-node library.
  • babel-preset-env: This package gives us access to forthcoming functionalities that node.js does not yet comprehend. New features are constantly being developed, thus it will probably take some time for NodeJS to incorporate them.
Terminal window
yarn add -D @babel/cli @babel/core @babel/node @babel/plugin-proposal-class-properties @babel/plugin-transform-runtime @babel/preset-env @babel/preset-typescript @babel/runtime babel-core babel-plugin-module-resolver babel-plugin-source-map-support

After that, we need to create a file called .babelrc in the project’s root directory, and we paste the following block of code there.

Terminal window
touch .babelrc

.babelrc

1
{
2
"presets": ["@babel/preset-env", "@babel/preset-typescript"],
3
"plugins": [
4
"@babel/plugin-proposal-class-properties",
5
"@babel/plugin-transform-runtime",
6
"source-map-support"
7
],
8
"sourceMaps": "inline"
9
}

Add the following line to the package.json file to compile, and build the code with babel:

1
{
2
"scripts": {
3
"build:compile": "npx babel src --extensions .ts --out-dir build --source-maps",
4
"build:types": "tsc"
5
}
6
}

Now we need to add .gitignore file to the project, and add the following line to it:

The .gitignore file tells Git which files to ignore when committing your project to the GitHub repository. gitignore is located in the root directory of your repo.

Terminal window
touch .gitignore

.gitignore

1
# Logs
2
logs
3
*.log
4
npm-debug.log*
5
yarn-debug.log*
6
yarn-error.log*
7
lerna-debug.log*
8
.pnpm-debug.log*
9
10
# Diagnostic reports (https://nodejs.org/api/report.html)
11
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
12
13
# Runtime data
14
pids
15
*.pid
16
*.seed
17
*.pid.lock
18
19
# Directory for instrumented libs generated by jscoverage/JSCover
20
lib-cov
21
22
# Coverage directory used by tools like istanbul
23
coverage
24
*.lcov
25
26
# nyc test coverage
27
.nyc_output
28
29
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
30
.grunt
31
32
# Bower dependency directory (https://bower.io/)
33
bower_components
34
35
# node-waf configuration
36
.lock-wscript
37
38
# Compiled binary addons (https://nodejs.org/api/addons.html)
39
build
40
build/Release
41
42
# Dependency directories
43
node_modules/
44
jspm_packages/
45
46
# Snowpack dependency directory (https://snowpack.dev/)
47
web_modules/
48
49
# TypeScript cache
50
*.tsbuildinfo
51
52
# Optional npm cache directory
53
.npm
54
55
# Optional eslint cache
56
.eslintcache
57
58
# Optional stylelint cache
59
.stylelintcache
60
61
# Microbundle cache
62
.rpt2_cache/
63
.rts2_cache_cjs/
64
.rts2_cache_es/
65
.rts2_cache_umd/
66
67
# Optional REPL history
68
.node_repl_history
69
70
# Output of 'npm pack'
71
*.tgz
72
73
# Yarn Integrity file
74
.yarn-integrity
75
76
# dotenv environment variable files
77
.env
78
.env.development.local
79
.env.test.local
80
.env.production.local
81
.env.local
82
83
# parcel-bundler cache (https://parceljs.org/)
84
.cache
85
.parcel-cache
86
87
# vuepress build output
88
.vuepress/dist
89
90
# vuepress v2.x temp and cache directory
91
.temp
92
.cache
93
94
# Docusaurus cache and generated files
95
.docusaurus
96
97
# Serverless directories
98
.serverless/
99
100
# FuseBox cache
101
.fusebox/
102
103
# DynamoDB Local files
104
.dynamodb/
105
106
# TernJS port file
107
.tern-port
108
109
# Stores VSCode versions used for testing VSCode extensions
110
.vscode-test
111
112
# yarn v2
113
.yarn/cache
114
.yarn/unplugged
115
.yarn/build-state.yml
116
.yarn/install-state.gz
117
.pnp.*

Code Formatting and Quality Tools

We will be using two tools in order to establish a standard that will be utilized by all project participants to maintain consistency in the coding style and the use of fundamental best practices:

  • Prettier: A tool that will help us to format our code consistently.
  • ESLint: A tool that will help us to enforce a consistent coding style.

Installing and Configuring Prettier

Prettier will handle the automated file formatting for us. Add it to the project right now.

Terminal window
yarn add -D prettier

Additionally, I advise getting the Prettier VS Code extension so that you may avoid using the command line tool and have VS Code take care of the file formatting for you. It’s still required to include it here even when it’s installed and set up in your project since VSCode will utilize your project’s settings.

We’ll create two files in the root:

  • .prettierrc: This file will contain the configuration for prettier.
  • .prettierignore: This file will contain the list of files that should be ignored by prettier.

.prettierrc

1
{
2
"trailingComma": "all",
3
"printWidth": 80,
4
"tabWidth": 2,
5
"useTabs": false,
6
"semi": false,
7
"singleQuote": true
8
}

.prettierignore

1
node_modules
2
build

I’ve listed the folders in that file that I don’t want Prettier to waste any time working on. If you’d want to disregard specific file types in groups, you may also use patterns like *.html.

Now we add a new script to package.json so we can run Prettier:

package.json

1
"scripts: {
2
...,
3
"prettier": "prettier --write \"src/**/*.ts\"",
4
"prettier:check": "prettier --check \"src/**/*.ts\"",
5
}

You can now run yarn prettier to format all files in the project, or yarn prettier:check to check if all files are formatted correctly.

Terminal window
yarn prettier:check
yarn prettier

to automatically format, repair, and save all files in your project that you haven’t ignored. My formatter updated around 7 files by default. The source control tab on the left of VS Code has a list of altered files where you may find them.

Installing and Configuring ESLint

We’ll begin with ESLint, which is a tool that will help us to enforce a consistent coding style, at first need to install the dependencies.

Terminal window
yarn add -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-config-standard eslint-plugin-import eslint-plugin-node eslint-plugin-prettier eslint-plugin-promise

We’ll create two files in the root:

  • .eslintrc: This file will contain the configuration for ESLint.
  • .eslintignore: This file will contain the list of files that should be ignored by ESLint.

.eslintrc

1
{
2
"parser": "@typescript-eslint/parser",
3
"parserOptions": {
4
"ecmaVersion": 12,
5
"sourceType": "module"
6
},
7
"plugins": ["@typescript-eslint"],
8
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
9
"rules": {
10
"@typescript-eslint/no-unused-vars": "error",
11
"@typescript-eslint/consistent-type-definitions": ["error", "interface"]
12
},
13
"env": {
14
"browser": true,
15
"es2021": true
16
}
17
}

.eslintignore

1
node_modules
2
build

Now we add a new script to package.json so we can run ESLint:

package.json

1
"scripts: {
2
...,
3
"lint": "eslint --ignore-path .eslintignore \"src/**/*.ts\" --fix",
4
"lint:check": "eslint --ignore-path .eslintignore \"src/**/*.ts\"",
5
}

You can test out your config by running:

You can now run yarn lint to format all files in the project, or yarn lint:check to check if all files are formatted correctly.

Terminal window
yarn lint:check
yarn lint

Git Hooks

Before moving on to component development, there is one more section on configuration. If you want to expand on this project in the future, especially with a team of other developers, keep in mind that you’ll want it to be as stable as possible. To get it right from the beginning is time well spent.

We’re going to use a program called Husky.

Installing and Configuring Husky

Husky is a tool for executing scripts at various git stages, such as add, commit, push, etc. We would like to be able to specify requirements and, provided our project is of acceptable quality, only enable actions like commit and push to proceed if our code satisfies those requirements.

To install Husky run

Terminal window
yarn add husky
yarn husky install

A .husky directory will be created in your project by the second command. Your hooks will be located here. As it is meant for other developers as well as yourself, make sure this directory is included in your code repository.

Add the following script to your package.json file:

package.json

1
"scripts: {
2
...,
3
"prepare": "husky install"
4
}

This will ensure Husky gets installed automatically when other developers run the project.

To create a hook run:

Terminal window
npx husky add .husky/pre-commit "yarn lint"

The aforementioned states that the yarn lint script must run and be successful before our commit may be successful. Success here refers to the absence of mistakes. You will be able to get warnings (remember in the ESLint config a setting of 1 is a warning and 2 is an error in case you want to adjust settings).

We’re going to add another one:

Terminal window
npx husky add .husky/pre-push "yarn build"

This makes sure that we can’t push to the remote repository until our code has built correctly. That sounds like a very acceptable requirement, don’t you think? By making this adjustment and attempting to push, feel free to test it.

Installing and Configuring Commitlint

Finally, we’ll add one more tool. Let’s make sure that everyone on the team is adhering to them as well (including ourselves! ), since we have been using a uniform format for all of our commit messages so far. For our commit messages, we may add a linter.

Terminal window
yarn add -D @commitlint/config-conventional @commitlint/cli

We will configure it using a set of common defaults, but since I occasionally forget what prefixes are available, I like to explicitly provide that list in a commitlint.config.js file:

Terminal window
touch commitlint.config.js

commitlint.config.js

1
// build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
2
// ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
3
// docs: Documentation only changes
4
// feat: A new feature
5
// fix: A bug fix
6
// perf: A code change that improves performance
7
// refactor: A code change that neither fixes a bug nor adds a feature
8
// style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
9
// test: Adding missing tests or correcting existing tests
10
module.exports = {
11
extends: ['@commitlint/config-conventional'],
12
rules: {
13
'body-leading-blank': [1, 'always'],
14
'body-max-line-length': [2, 'always', 100],
15
'footer-leading-blank': [1, 'always'],
16
'footer-max-line-length': [2, 'always', 100],
17
'header-max-length': [2, 'always', 100],
18
'scope-case': [2, 'always', 'lower-case'],
19
'subject-case': [
20
2,
21
'never',
22
['sentence-case', 'start-case', 'pascal-case', 'upper-case'],
23
],
24
'subject-empty': [2, 'never'],
25
'subject-full-stop': [2, 'never', '.'],
26
'type-case': [2, 'always', 'lower-case'],
27
'type-empty': [2, 'never'],
28
'type-enum': [
29
2,
30
'always',
31
[
32
'build',
33
'chore',
34
'ci',
35
'docs',
36
'feat',
37
'fix',
38
'perf',
39
'refactor',
40
'revert',
41
'style',
42
'test',
43
'translation',
44
'security',
45
'changeset',
46
],
47
],
48
},
49
};

Afterward, use Husky to enable commitlint by using:

Terminal window
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'

now push your changes to the remote repository and you’ll be able to commit with a valid commit message.

Terminal window
git add .
Terminal window
git commit -m "ci: eslint | prettier | husky"
Terminal window
╭─mkabumattar@mkabumattar in repo: template-express-typescript-blueprint on main [+] is  v0.0.0 via  v18.4.0 took 41ms
╰─λ git commit -m "ci: eslint | prettier | husky"
yarn run v1.22.18
$ eslint --ignore-path .eslintignore "src/**/*.ts" --fix
Done in 1.31s.
[main 7fbc14f] ci: eslint | prettier | husky
17 files changed, 4484 insertions(+)
create mode 100644 .babelrc
create mode 100644 .eslintignore
create mode 100644 .eslintrc
create mode 100644 .gitattributes
create mode 100644 .gitignore
create mode 100755 .husky/commit-msg
create mode 100755 .husky/pre-commit
create mode 100755 .husky/pre-push
create mode 100644 .npmrc
create mode 100644 .nvmrc
create mode 100644 .prettierignore
create mode 100644 .prettierrc
create mode 100644 commitlint.config.js
create mode 100644 package.json
create mode 100644 src/index.ts
create mode 100644 tsconfig.json
create mode 100644 yarn.lock
Terminal window
git push -u origin main
Terminal window
╭─mkabumattar@mkabumattar in repo: template-express-typescript-blueprint on main [⇡1] is v0.0.0 via  v18.4.0 took 2s
╰─λ git push -u origin main
yarn run v1.22.18
error Command "build" not found.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
husky - pre-push hook exited with code 1 (error)
error: failed to push some refs to 'github.com:MKAbuMattar/template-express-typescript-blueprint.git'

now we need to make sure that we can push to the remote repository, we forgot to add the build command to the .husky/pre-push file.

1
"scripts": {
2
"build": "yarn build:compile && yarn build:types",
3
...,
4
}
Terminal window
╭─mkabumattar@mkabumattar in repo: template-express-typescript-blueprint on main [⇡1] is v0.0.0 via  v18.4.0 took 2s
[🔴] × git push -u origin main
yarn run v1.22.18
$ yarn build:compile && yarn build:types
$ npx babel src --extensions .ts --out-dir build --source-maps
Successfully compiled 1 file with Babel (360ms).
$ tsc
Done in 2.63s.
Enumerating objects: 21, done.
Counting objects: 100% (21/21), done.
Delta compression using up to 4 threads
Compressing objects: 100% (16/16), done.
Writing objects: 100% (20/20), 79.42 KiB | 9.93 MiB/s, done.
Total 20 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (1/1), done.
To github.com:MKAbuMattar/template-express-typescript-blueprint.git
1583ab9..7fbc14f main -> main
branch 'main' set up to track 'origin/main'.

Create somple setup express, typescript and babel application

Create a file structure like this:

1
├── src
2
│   ├── index.ts
3
│   └── bin
4
│   └── www.ts
5
├────── constants
6
│   └── api.constant.ts
7
│   └── http.code.constant.ts
8
│   └── http.reason.constant.ts
9
│   └── message.constant.ts
10
├────── interfaces
11
│   └── controller.interface.ts
12
├────── middlewares
13
│   └── error.middleware.ts
14
├────── utils
15
│   └── logger.util.ts
16
│   └── exceptions
17
│   └── http.exception.ts
18
├── .babelrc
19
├── .eslintignore
20
├── .eslintrc
21
├── .gitattributes
22
├── .gitignore
23
├── .npmrc
24
├── .nvmrc
25
├── .prettierignore
26
├── .prettierrc
27
├── commitlint.config.js
28
├── package.json
29
├── README.md
30
├── tsconfig.json
31
├── yarn.lock

start to add express and typescript dependencies:

Terminal window
yarn add express
Terminal window
yarn add -D @types/express

New we’ll add a new package:

  • compression: Your Node.js app’s main file contains middleware for compression. GZIP, which supports a variety of compression techniques, will then be enabled. Your JSON response and any static file replies will be smaller as a result.
Terminal window
yarn add compression
  • cookie-parser: Your Node.js app’s main file contains middleware for cookie-parser. This middleware will parse the cookies in the request and set them as properties of the request object.
Terminal window
yarn add cookie-parser
  • core-js: Your Node.js app’s main file contains middleware for core-js. This middleware will add the necessary polyfills to your application.
Terminal window
yarn add core-js
  • cors: Your Node.js app’s main file contains middleware for cors. This middleware will add the necessary headers to your application.
Terminal window
yarn add cors
  • helmet: Your Node.js app’s main file contains middleware for helmet. This middleware will add security headers to your application.
Terminal window
yarn add helmet
  • regenerator-runtime: Your Node.js app’s main file contains middleware for regenerator-runtime. This middleware will add the necessary polyfills to your application.
Terminal window
yarn add regenerator-runtime

after that we need to add the type for the dependencies:

Terminal window
yarn add -D @types/compression @types/cookie-parser @types/core-js @types/cors @types/regenerator-runtime

now we’ll start with create constants and we’ll add new things after that:

api.constant.ts

1
class Api {
2
public static readonly ROOT: string = '/';
3
4
public static readonly API: string = '/api';
5
}
6
export default Api;

http.code.constant.ts

1
class HttpCode {
2
public static readonly CONTINUE: number = 100;
3
4
public static readonly SWITCHING_PROTOCOLS: number = 101;
5
6
public static readonly PROCESSING: number = 102;
7
8
public static readonly OK: number = 200;
9
10
public static readonly CREATED: number = 201;
11
12
public static readonly ACCEPTED: number = 202;
13
14
public static readonly NON_AUTHORITATIVE_INFORMATION: number = 203;
15
16
public static readonly NO_CONTENT: number = 204;
17
18
public static readonly RESET_CONTENT: number = 205;
19
20
public static readonly PARTIAL_CONTENT: number = 206;
21
22
public static readonly MULTI_STATUS: number = 207;
23
24
public static readonly ALREADY_REPORTED: number = 208;
25
26
public static readonly IM_USED: number = 226;
27
28
public static readonly MULTIPLE_CHOICES: number = 300;
29
30
public static readonly MOVED_PERMANENTLY: number = 301;
31
32
public static readonly MOVED_TEMPORARILY: number = 302;
33
34
public static readonly SEE_OTHER: number = 303;
35
36
public static readonly NOT_MODIFIED: number = 304;
37
38
public static readonly USE_PROXY: number = 305;
39
40
public static readonly SWITCH_PROXY: number = 306;
41
42
public static readonly TEMPORARY_REDIRECT: number = 307;
43
44
public static readonly BAD_REQUEST: number = 400;
45
46
public static readonly UNAUTHORIZED: number = 401;
47
48
public static readonly PAYMENT_REQUIRED: number = 402;
49
50
public static readonly FORBIDDEN: number = 403;
51
52
public static readonly NOT_FOUND: number = 404;
53
54
public static readonly METHOD_NOT_ALLOWED: number = 405;
55
56
public static readonly NOT_ACCEPTABLE: number = 406;
57
58
public static readonly PROXY_AUTHENTICATION_REQUIRED: number = 407;
59
60
public static readonly REQUEST_TIMEOUT: number = 408;
61
62
public static readonly CONFLICT: number = 409;
63
64
public static readonly GONE: number = 410;
65
66
public static readonly LENGTH_REQUIRED: number = 411;
67
68
public static readonly PRECONDITION_FAILED: number = 412;
69
70
public static readonly PAYLOAD_TOO_LARGE: number = 413;
71
72
public static readonly REQUEST_URI_TOO_LONG: number = 414;
73
74
public static readonly UNSUPPORTED_MEDIA_TYPE: number = 415;
75
76
public static readonly REQUESTED_RANGE_NOT_SATISFIABLE: number = 416;
77
78
public static readonly EXPECTATION_FAILED: number = 417;
79
80
public static readonly IM_A_TEAPOT: number = 418;
81
82
public static readonly METHOD_FAILURE: number = 420;
83
84
public static readonly MISDIRECTED_REQUEST: number = 421;
85
86
public static readonly UNPROCESSABLE_ENTITY: number = 422;
87
88
public static readonly LOCKED: number = 423;
89
90
public static readonly FAILED_DEPENDENCY: number = 424;
91
92
public static readonly UPGRADE_REQUIRED: number = 426;
93
94
public static readonly PRECONDITION_REQUIRED: number = 428;
95
96
public static readonly TOO_MANY_REQUESTS: number = 429;
97
98
public static readonly REQUEST_HEADER_FIELDS_TOO_LARGE: number = 431;
99
100
public static readonly UNAVAILABLE_FOR_LEGAL_REASONS: number = 451;
101
102
public static readonly INTERNAL_SERVER_ERROR: number = 500;
103
104
public static readonly NOT_IMPLEMENTED: number = 501;
105
106
public static readonly BAD_GATEWAY: number = 502;
107
108
public static readonly SERVICE_UNAVAILABLE: number = 503;
109
110
public static readonly GATEWAY_TIMEOUT: number = 504;
111
112
public static readonly HTTP_VERSION_NOT_SUPPORTED: number = 505;
113
114
public static readonly VARIANT_ALSO_NEGOTIATES: number = 506;
115
116
public static readonly INSUFFICIENT_STORAGE: number = 507;
117
118
public static readonly LOOP_DETECTED: number = 508;
119
120
public static readonly NOT_EXTENDED: number = 510;
121
122
public static readonly NETWORK_AUTHENTICATION_REQUIRED: number = 511;
123
124
public static readonly NETWORK_CONNECT_TIMEOUT_ERROR: number = 599;
125
}
126
127
export default HttpCode;

http.reason.constant.ts

1
class HttpReason {
2
public static readonly CONTINUE: string = 'Continue';
3
4
public static readonly SWITCHING_PROTOCOLS: string = 'Switching Protocols';
5
6
public static readonly PROCESSING: string = 'Processing';
7
8
public static readonly OK: string = 'OK';
9
10
public static readonly CREATED: string = 'Created';
11
12
public static readonly ACCEPTED: string = 'Accepted';
13
14
public static readonly NON_AUTHORITATIVE_INFORMATION: string =
15
'Non-Authoritative Information';
16
17
public static readonly NO_CONTENT: string = 'No Content';
18
19
public static readonly RESET_CONTENT: string = 'Reset Content';
20
21
public static readonly PARTIAL_CONTENT: string = 'Partial Content';
22
23
public static readonly MULTI_STATUS: string = 'Multi-Status';
24
25
public static readonly ALREADY_REPORTED: string = 'Already Reported';
26
27
public static readonly IM_USED: string = 'IM Used';
28
29
public static readonly MULTIPLE_CHOICES: string = 'Multiple Choices';
30
31
public static readonly MOVED_PERMANENTLY: string = 'Moved Permanently';
32
33
public static readonly MOVED_TEMPORARILY: string = 'Moved Temporarily';
34
35
public static readonly SEE_OTHER: string = 'See Other';
36
37
public static readonly NOT_MODIFIED: string = 'Not Modified';
38
39
public static readonly USE_PROXY: string = 'Use Proxy';
40
41
public static readonly SWITCH_PROXY: string = 'Switch Proxy';
42
43
public static readonly TEMPORARY_REDIRECT: string = 'Temporary Redirect';
44
45
public static readonly BAD_REQUEST: string = 'Bad Request';
46
47
public static readonly UNAUTHORIZED: string = 'Unauthorized';
48
49
public static readonly PAYMENT_REQUIRED: string = 'Payment Required';
50
51
public static readonly FORBIDDEN: string = 'Forbidden';
52
53
public static readonly NOT_FOUND: string = 'Not Found';
54
55
public static readonly METHOD_NOT_ALLOWED: string = 'Method Not Allowed';
56
57
public static readonly NOT_ACCEPTABLE: string = 'Not Acceptable';
58
59
public static readonly PROXY_AUTHENTICATION_REQUIRED: string =
60
'Proxy Authentication Required';
61
62
public static readonly REQUEST_TIMEOUT: string = 'Request Timeout';
63
64
public static readonly CONFLICT: string = 'Conflict';
65
66
public static readonly GONE: string = 'Gone';
67
68
public static readonly LENGTH_REQUIRED: string = 'Length Required';
69
70
public static readonly PRECONDITION_FAILED: string = 'Precondition Failed';
71
72
public static readonly PAYLOAD_TOO_LARGE: string = 'Payload Too Large';
73
74
public static readonly REQUEST_URI_TOO_LONG: string = 'Request URI Too Long';
75
76
public static readonly UNSUPPORTED_MEDIA_TYPE: string =
77
'Unsupported Media Type';
78
79
public static readonly REQUESTED_RANGE_NOT_SATISFIABLE: string =
80
'Requested Range Not Satisfiable';
81
82
public static readonly EXPECTATION_FAILED: string = 'Expectation Failed';
83
84
public static readonly IM_A_TEAPOT: string = "I'm a teapot";
85
86
public static readonly METHOD_FAILURE: string = 'Method Failure';
87
88
public static readonly MISDIRECTED_REQUEST: string = 'Misdirected Request';
89
90
public static readonly UNPROCESSABLE_ENTITY: string = 'Unprocessable Entity';
91
92
public static readonly LOCKED: string = 'Locked';
93
94
public static readonly FAILED_DEPENDENCY: string = 'Failed Dependency';
95
96
public static readonly UPGRADE_REQUIRED: string = 'Upgrade Required';
97
98
public static readonly PRECONDITION_REQUIRED: string =
99
'Precondition Required';
100
101
public static readonly TOO_MANY_REQUESTS: string = 'Too Many Requests';
102
103
public static readonly REQUEST_HEADER_FIELDS_TOO_LARGE: string =
104
'Request Header Fields Too Large';
105
106
public static readonly UNAVAILABLE_FOR_LEGAL_REASONS: string =
107
'Unavailable For Legal Reasons';
108
109
public static readonly INTERNAL_SERVER_ERROR: string =
110
'Internal Server Error';
111
112
public static readonly NOT_IMPLEMENTED: string = 'Not Implemented';
113
114
public static readonly BAD_GATEWAY: string = 'Bad Gateway';
115
116
public static readonly SERVICE_UNAVAILABLE: string = 'Service Unavailable';
117
118
public static readonly GATEWAY_TIMEOUT: string = 'Gateway Timeout';
119
120
public static readonly HTTP_VERSION_NOT_SUPPORTED: string =
121
'HTTP Version Not Supported';
122
123
public static readonly VARIANT_ALSO_NEGOTIATES: string =
124
'Variant Also Negotiates';
125
126
public static readonly INSUFFICIENT_STORAGE: string = 'Insufficient Storage';
127
128
public static readonly LOOP_DETECTED: string = 'Loop Detected';
129
130
public static readonly NOT_EXTENDED: string = 'Not Extended';
131
132
public static readonly NETWORK_AUTHENTICATION_REQUIRED: string =
133
'Network Authentication Required';
134
135
public static readonly NETWORK_CONNECT_TIMEOUT_ERROR: string =
136
'Network Connect Timeout Error';
137
}
138
139
export default HttpReason;

message.constant.ts

1
class Message {
2
public static readonly API_WORKING: string = 'API is working';
3
4
public static readonly SOMETHING_WENT_WRONG: string = 'Something went wrong';
5
}
6
export default Message;

utils/exception/http.exception.ts

1
class HttpException extends Error {
2
public statusCode: number;
3
4
public statusMsg: string;
5
6
public msg: string;
7
8
constructor(statusCode: number, statusMsg: string, msg: any) {
9
super(msg);
10
this.statusCode = statusCode;
11
this.statusMsg = statusMsg;
12
this.msg = msg;
13
}
14
}
15
16
export default HttpException;

error.middleware.ts

1
import {Request, Response, NextFunction} from 'express';
2
import HttpException from '@/utils/exceptions/http.exception';
3
4
// http constant
5
import ConstantHttpCode from '@/constants/http.code.constant';
6
import ConstantHttpReason from '@/constants/http.reason.constant';
7
8
// message constant
9
import ConstantMessage from '@/constants/message.constant';
10
11
const errorMiddleware = (
12
error: HttpException,
13
_req: Request,
14
res: Response,
15
next: NextFunction,
16
): Response | void => {
17
try {
18
const statusCode =
19
error.statusCode || ConstantHttpCode.INTERNAL_SERVER_ERROR;
20
const statusMsg =
21
error.statusMsg || ConstantHttpReason.INTERNAL_SERVER_ERROR;
22
const msg = error.msg || ConstantMessage.SOMETHING_WENT_WRONG;
23
24
return res.status(statusCode).send({
25
status: {
26
code: statusCode,
27
msg: statusMsg,
28
},
29
msg: msg,
30
});
31
} catch (err) {
32
return next(err);
33
}
34
};
35
36
export default errorMiddleware;

controller.interface.ts

1
import {Router} from 'express';
2
3
interface Controller {
4
path: string;
5
router: Router;
6
}
7
8
export default Controller;

index.ts

1
import express, {Application, Request, Response, NextFunction} from 'express';
2
3
import compression from 'compression';
4
import cookieParser from 'cookie-parser';
5
import cors from 'cors';
6
import helmet from 'helmet';
7
8
import ErrorMiddleware from './middlewares/error.middleware';
9
import HttpException from './utils/exceptions/http.exception';
10
import Controller from './interfaces/controller.interface';
11
12
// api constant
13
import ConstantAPI from './constants/api.constant';
14
15
// message constant
16
import ConstantMessage from './constants/message.constant';
17
18
// http constant
19
import ConstantHttpCode from './constants/http.code.constant';
20
import ConstantHttpReason from './constants/http.reason.constant';
21
22
class App {
23
public app: Application;
24
25
constructor(controllers: Controller[]) {
26
this.app = express();
27
28
this.initialiseConfig();
29
this.initialiseRoutes();
30
this.initialiseControllers(controllers);
31
this.initialiseErrorHandling();
32
}
33
34
private initialiseConfig(): void {
35
this.app.use(express.json());
36
this.app.use(express.urlencoded({extended: true}));
37
this.app.use(cookieParser());
38
this.app.use(compression());
39
this.app.use(cors());
40
this.app.use(helmet());
41
}
42
43
private initialiseRoutes(): void {
44
this.app.get(
45
ConstantAPI.ROOT,
46
(_req: Request, res: Response, next: NextFunction) => {
47
try {
48
return res.status(ConstantHttpCode.OK).json({
49
status: {
50
code: ConstantHttpCode.OK,
51
msg: ConstantHttpReason.OK,
52
},
53
msg: ConstantMessage.API_WORKING,
54
});
55
} catch (err: any) {
56
return next(
57
new HttpException(
58
ConstantHttpCode.INTERNAL_SERVER_ERROR,
59
ConstantHttpReason.INTERNAL_SERVER_ERROR,
60
err.message,
61
),
62
);
63
}
64
},
65
);
66
}
67
68
private initialiseControllers(controllers: Controller[]): void {
69
controllers.forEach((controller: Controller) => {
70
this.app.use(ConstantAPI.API, controller.router);
71
});
72
}
73
74
private initialiseErrorHandling(): void {
75
this.app.use(ErrorMiddleware);
76
}
77
}
78
79
export default App;

www.ts

1
#!/usr/bin/env ts-node
2
3
import 'core-js/stable';
4
import 'regenerator-runtime/runtime';
5
6
import http from 'http';
7
import App from '..';
8
9
// controllers
10
11
const {app} = new App([]);
12
13
/**
14
* Normalize a port into a number, string, or false.
15
*/
16
const normalizePort = (val: any) => {
17
const port = parseInt(val, 10);
18
19
if (Number.isNaN(port)) {
20
// named pipe
21
return val;
22
}
23
24
if (port >= 0) {
25
// port number
26
return port;
27
}
28
29
return false;
30
};
31
32
const port = normalizePort('3030');
33
app.set('port', port);
34
35
/**
36
* Create HTTP server.
37
*/
38
const server = http.createServer(app);
39
40
/**
41
* Event listener for HTTP server "error" event.
42
*/
43
const onError = (error: any) => {
44
if (error.syscall !== 'listen') {
45
throw error;
46
}
47
48
const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;
49
50
// handle specific listen errors with friendly messages
51
switch (error.code) {
52
case 'EACCES':
53
console.error(`${bind} requires elevated privileges`);
54
process.exit(1);
55
break;
56
case 'EADDRINUSE':
57
console.error(`${bind} is already in use`);
58
process.exit(1);
59
break;
60
default:
61
throw error;
62
}
63
};
64
65
/**
66
* Event listener for HTTP server "listening" event.
67
*/
68
const onListening = () => {
69
const addr = server.address();
70
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr?.port}`;
71
console.info(`Listening on ${bind}`);
72
};
73
74
server.listen(port);
75
server.on('error', onError);
76
server.on('listening', onListening);

To run the app, and start tarcking the server, with the changes, we need to add new dependency.

Concurrently: is a tool to run multiple tasks at the same time.

Terminal window
yarn add -D concurrently

Then, we’ll add the following command to scripts section of package.json:

1
"scripts": {
2
"start": "node build/bin/www.js",
3
"clean": "rm -rf build",
4
"build": "yarn clean && concurrently yarn:build:*",
5
"build:compile": "npx babel src --extensions .ts --out-dir build --source-maps",
6
"build:types": "tsc",
7
"dev": "concurrently yarn:dev:* --kill-others \"nodemon --exec node build/bin/www.js\"",
8
"dev:compile": "npx babel src --extensions .ts --out-dir build --source-maps --watch",
9
"dev:types": "tsc --watch",
10
...,
11
}

New you can run the application with yarn start or yarn dev, and you can also run the application with yarn build to create a production version.

Terminal window
yarn dev
yarn start
yarn build

Summary

Finally, after compilation, we can now need to deploy the compiled version in the NodeJS production server.

All code from this tutorial as a complete package is available in this repository.

Related Posts

Check out some of our other posts

Setting up Node JS, Express, MongoDB, Prettier, ESLint and Husky Application with Babel and authentication as an example

Setting up Node JS, Express, MongoDB, Prettier, ESLint and Husky Application with Babel and authentication as an example

Introduction All code from this tutorial as a complete package is available in this repository. If you find this tutorial helpful, please share

read more
Setting up JWT Authentication in Typescript with Express, MongoDB, Babel, Prettier, ESLint, and Husky: Part 2

Setting up JWT Authentication in Typescript with Express, MongoDB, Babel, Prettier, ESLint, and Husky: Part 2

Introduction Why do we even need an authentication mechanism in an application? in my opinion, it doesn't need to be explained. The phrases authentication and authorization have likely crossed yo

read more
Introduction to Spring Boot Framework

Introduction to Spring Boot Framework

Introduction For creating web apps and microservices, many developers utilize the Spring Boot framework. The fact that it is built on top of the Spring Framework and offers a number of advantages

read more
RESTful API vs. GraphQL: Which API is the Right Choice for Your Project?

RESTful API vs. GraphQL: Which API is the Right Choice for Your Project?

TL;DR When deciding between RESTful and GraphQL APIs for a data analysis and display application, it is important to consider the advantages and disadvantages of each. RESTful APIs have been arou

read more
Decoding REST API Architecture: A Comprehensive Guide for Developers

Decoding REST API Architecture: A Comprehensive Guide for Developers

Introduction Hey there, fellow developers! Buckle up because we're about to dive into the crazy world of REST API architecture. Prepare to decode the mysterious differences between REST API and R

read more
Mastering Caching Strategies with Redis Cache: Boosting Performance in Node.js and TypeScript

Mastering Caching Strategies with Redis Cache: Boosting Performance in Node.js and TypeScript

Introduction In the ever-evolving realm of software development, the pursuit of optimizing application performance is a perpetual endeavor. Among the arsenal of strategies to attain this goal, th

read more