cft
Become a CreatorSign inGet Started

How to set up a Node.js backend using Express.js and TypeScript

Node.js is one of the most popular node frameworks for web developers today, and when combined with Express.js, it can be even more powerful.


user

Stéphane Sulikowski

4 months ago | 4 min read
Follow

set-nodejs-backend-using-expressjs-typescript-zpvzh

Node.js is one of the most popular node frameworks for web developers today, and when combined with Express.js, it can be even more powerful.

Express is a node framework that lets you build node apps in an easy way by using node’s built-in middleware concept. This has many benefits like making your code more readable and maintainable, abstracting away boilerplate patterns like route handlers to make them reusable, etc.

TypeScript is a superset of JavaScript that compiles to clean JavaScript output without any runtime errors or performance issues! It has many great features like static typing, modules, interfaces, and more.

In this blog post, we’ll see how to set up a node.js backend using Express.js and TypeScript.

Installation

If Node.js is not installed on your computer, download the proper installation package on https://nodejs.org and proceed to the installation.

Then, we need to install the Express.js and TypeScript dependencies. For this, we can use npm:

npm install express typescript --save-dev

The — dev option will write the dependency as used for the development only. It will not be installed in a production environment.

Create a new directory to store your project, and navigate inside with your terminal and initialise the project with :

npm init -y

Install types

It’s recommended to install the types so TypeScript can use type declarations :

npm install @types/node @types/express --save-dev

Setup TypeScript with tsconfig.json

Create a file named tsconfig.json that is the configuration file for TypeScript, and write the following options :

{

"compilerOptions": {

"module": "commonjs",

"esModuleInterop": true,

"target": "es6",

"noImplicitAny": true,

"moduleResolution": "node",

"sourceMap": true,

"outDir": "dist",

"baseUrl": ".",

"paths": {

"*": [

"node_modules/*"

]

}

},

"include": [

"src/**/*"

]

}

Please note that all the code has to be placed in a folder named « src » to be processed.

Add scripts to the package.json file

We will add the following scripts to the package.json file to process and compile the Typescript code at start :

"scripts": {

"prebuild": "tslint -c tslint.json -p tsconfig.json --fix",

"build": "tsc",

"prestart": "npm run build",

"start": "node ."

},

Add the main entry in the package.json file

We will now tell node that the main entry point for our app is located in the dist/index.js file:

"main": "dist/index.js",

Add a linter

We will add now a linter to ensure code quality. It’s super handy because the linter check things beyond code syntax.

Again let’s use a command in the terminal :

npm install --save-dev tslint

We will also create a configuration file and write the following options :

{

"defaultSeverity": "error",

"extends": [

"tslint:recommended"

],

"jsRules": {},

"rules": {

"trailing-comma": [ false ],

"no-console": [true, "warning"]

},

"rulesDirectory": []

}

Please note that we have an option that prevents usage of the console, but with a warning only and will not block the output if we decide to use it anyway.

… and configuration is done !

Create a server

Now we can create an express app using node’s App module.

As we use TypeScript, please be aware that the includes are written in a different way :

Insead of

const express = require('express');

We will write

import express from 'express';

As we declared in the configuration, the main file is index.ts that is located in the « src » directory.

We create the directory and file if needed and we write the following code:

import express from 'express';

const app = express();

// declare a route with a response

app.get('/', (req, res) => {

res.send("What's up doc ?!");

});

// start the server

app.listen(8081, () => {

console.log(`server running : http://localhost:8081`);

});

Now time to run the server, in the root directory of the project we will write:

npm run start

The code will be compiled, and when the process is finishes we should see «server running : http://localhost:8081 ».

Now we can type http://localhost:8081 in our browser, and … 🥳

One more thing

As you could see we wrote the server host and port in the code.

To get more code friendly, we should write these infos as environment variables.

To do so let’s add a npm package named dotenv:

npm install dotenv --save

We will create a file at the root of our project named .env

In this file let’s add the following information:

BACK_HOST=localhost

BACK_PORT=8081

And in our index.ts file, let’s call these variables and use them for our server:

import express from 'express';

import dotenv from 'dotenv';

const app = express();

dotenv.config();

// declare a route with a response

app.get('/', (req, res) => {

res.send("What's up doc ?!");

});

// start the server

app.listen(process.env.BACK_PORT, () => {

console.log(`server running : http://${process.env.BACK_HOST}:${process.env.BACK_PORT}`);

});

Please note that to access an env variable, follow the syntax:

process.env.NAME_OF_YOUR_VARIABLE_DECLARED_IN_THE_ENV_FILE

Conclusion

In this post, we’ve seen how to set up a node.js backend using Express.js and TypeScript. We’ve also seen some of the benefits that come with using these technologies together.

I hope you found this useful!

Happy coding !

Upvote


user
Created by

Stéphane Sulikowski

Follow

Full stack web developer, nocoder, product manager


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles