TypeScript Backend Project Setup

TypeScript Backend Project Setup

Trust me, it is very easy

Introduction

Back-end web development is a part of web development. Back-end development primarily deals with the interaction of the front end with the database of an application. Mostly, back-end developers build APIs so that the front end can store and fetch data from the database. Back-end developers also need to have some knowledge of Database Management Systems so that they can query the database correctly depending on the requests made by the front end.

Various frameworks are used for back-end web development, in this series we are going to work on Node.js and Express.js and use Typescript as our programming language. In this article, I will go through the steps of how you can set up your local development environment for a Typescript backend project.

Before that, let's learn something about the frameworks we are going to use.

Pre-requisite Knowledge

Node.js

Many people have a misconception that Node.js is a Javascript framework that we use in backend web development. But that is not correct. Node.js is a Javascript runtime environment. Now, what is a runtime environment? To put it simply, a runtime environment is an environment where a project or application is executed.

Coming back to Node.js, according to the official Node.js website,

As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.

To build any project in Javascript, you need to have Node.js and the Node Package Manager (npm) installed. You can install Node from its official website (click here).

Express.js

While Node.js is the runtime environment without which we cannot run our JS or TS projects, Express.js is the framework that we are going to use to build our backend project. Express.js has many methods which we are going to use extensively. According to the official website of Express.js,

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Also,

With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.

We shall come into the installation steps in the next step of this article.

Pre-requisites

There are 2 steps that we need to cover. Those are:

  • Install Node.js
  • Install the typescript npm package globally in our system
  • Install VS Code or any other text editor (I will assume that you already have that installed. If not download from the official website)

Install Node.js

Steps -

  • Go to the Node.js official website
  • Follow the instructions to install the latest LTS version for your Operating System.

After installing, go to your terminal (for Linux and Mac users) or command line (for Windows users), and type the following commands to check the versions of Node and npm installed. If installed correctly, there won't be any errors

node --version && npm --version

The output (if everything has been installed correctly) should be as follows:

v16.18.0
8.19.2

Install Typescript npm package

This is a very important step if you want to use Typescript as your language of choice when building backend projects. After node and npm have been installed correctly, you can carry out this step. Open your terminal or command line, and type the following command

npm install -g typescript

Note: For Linux Users, you may need to use sudo for the command to work

The -g flag installs the typescript package globally across our system.

If both these steps have been completed, then we can proceed to the main part of the article.

The how-to

If you have completed all the steps in the previous sections, this means that you are now ready to move into the actual setup of our backend project. In this section, I will discuss:

  • How to initialize a project
  • Which packages do we typically need for the Node.js project
  • Folder structure that may be followed such that our codebase remains clean

How to Initialize the project

This is by far the easiest step. In this step, we need to set up the Node.js project and initialize Typescript for the project.

Initialize Node.js project

The first thing you need to do is to go to your desired location in your system and create an empty folder. Name the folder anything you like, and make sure it is related to the project you are working on. For this article let's name it nodejs-typescript.

mkdir nodejs-typescript && cd nodejs-typescript

After the folder has been created, change your directory to the newly created directory and open your terminal.

For initializing the Node.js project, write the following command:

npm init -y

If you open VS Code for this directory, you shall see that a package.json file has been created for your project. The contents are as follows:

{
  "name": "nodejs-typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

What does this file do? The package.json file stores certain metadata for the project, like scripts for development, testing, and deployment, as well as which packages are being used for this project. We shall witness this as we progress through this article.

Initialize Typescript

If you have successfully initialized Node.js for your project, then this step should be very easy. Open up a terminal in your VS Code or you can open a separate terminal and change directories to your project. Then, write the following command:

tsc --init

If you installed the typescript global package correctly, then the following output will be shown and a tsconfig.json shall be created.

Created a new tsconfig.json with:                                                                                       

  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true


You can learn more at https://aka.ms/tsconfig

Installing required packages

So we have initialized our Node.js project and initialized it for supporting Typescript. The next step involved installing the required packages.

Firstly, we need to install express, because it is the essential package to build our REST API backend.

To install express, we need to run the following command in our terminal, inside VS Code,

npm install --save express

On running this command you will see a change in your package.json file.

{
  "name": "nodejs-typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

As you can see, the name of the express package and its version has been written to the package.json file.

In the same way, you can install the following packages:

  • express-validator
  • jsonwebtoken (To generate JWT Authentication tokens)
  • cors (To allow CORS)
  • bcryptjs (For hashing any data required)
  • crypto (Also to encode and decode sensitive data)
  • dotenv (To access environment variables)
  • mongoose (To connect with MongoDB database)

In addition to these, since we are using typescript, you also need to install some more packages which include the type definitions of the above packages. Let's take express for instance. To work with Typescript, we also need to install the package @types/express as a dev dependency. Let's see how.

npm install --save-dev @types/express

When this is done successfully, you shall see no errors when using express with Typescript. Similarly, install other type definitions packages that you need, and you are ready to go.

Folder structure

To build any good project, you need to have a clean and organized codebase. And that is not only for your future self, it is also helpful for team members that you collaborate with. That can be achieved if you follow a fixed folder structure to divide your files into modules of sorts. In this section, I would like to describe the file structure that I like to follow when building Node.js projects. I will first show the project structure, and then describe what each folder or module does.

This is the folder structure, that I generally follow:

nodejs-typescript/
├─ node_modules/
├─ src/
│  ├─ config/
│  ├─ controllers/
│  ├─ dtos/
│  ├─ middlewares/
│  ├─ models/
│  ├─ routes/
│  ├─ services/
│  ├─ shared/
│  ├─ utils/
│  ├─ app.ts
├─ .gitignore
├─ package.json
├─ README.md
├─ tsconfig.json

Now let's go through what role each folder and file has for this structure.

Function of each folder

The src folder contains all the code for the project.

  • config - This folder contains all the configuration files that you need for any project. For example, configuration files for connecting to the Database server, configuration for Swagger Documentation, etc.

  • controllers - This folder contains all the files for connecting requests to their particular services. Services are the only files in the code, that add, update, delete, and get data from the database. All other files connect to the database via the functions of different services. If a user makes a GET request, the request goes first to the controller, and then the required service is called by the controller.

  • dtos - DTO stands for Data Transfer Object. Thus the dtos folder contains all the Object structures that you would need for this project. Creating DTOs helps us to serialize and deserialize the JSON objects that we get from the database or the JSON object that we store in the database. In Node.js projects, mostly we use MongoDB as our database, which is a NoSQL database. In a NoSQL database, data is usually stored in the form of JSON, thus creating a DTO reflecting the properties required helps in efficient data transfer to and from the database.

  • middlewares - Middlewares are certain special functions that have access to the request, response, and the next middleware function in an application's request-response cycle. You can code middleware functions for validating user data, certain user input, etc. Functionalities offered by middleware functions are executing any code, ending the request-response cycle, making necessary changes to the request body, and calling the next middleware function present in the stack.

  • models - The models folder contains all the data models that we want to use in our project. Similar to dtos, which provide the bare backbone structure for data objects, models are the data interfaces that we post or get from the database.

  • routes - The routes folder contains all the routes of the API that we have. Let's say that our domain is https://domain-a.com. Then for registration of a new user, if we declare the route to be a POST request to /user/register, then from the front end a request has to be made to https://domain-a.com/user/register with the necessary request body. All the routes and the type of HTTP request to be made for each request are defined in the routes folder.

  • services - This folder is by far the most important part of our codebase. All the functions related to the CRUD operations, i.e., Create, Read, Update, and Delete operations are defined in this folder. The controller for each request, calls the necessary services function according to the request type.

  • shared - This folder contains any extra function which is shared by the entire project

  • utils - This folder contains the functions that I use in almost any Node.js package
  • app.ts - This is the entry file to our project. Every route, controller, and service is diverted from this file.

Conclusion

If you have reached here, congratulations! You have successfully initialized your Node.js project and made it suitable for Typescript support, and build APIs. We shall dive more into how to code the REST API in later articles. Till now, we have covered a lot of things, and you need to understand each and every point we have covered to build a good base of knowledge to further proceed towards making projects. We shall build some really good projects in the subsequent articles.


All my articles are listed here

Do consider subscribing to my newsletter. So that every time I post a new article, you get notified of it in your email.

Follow me on :