Best Node.js and Express Server Setup With TypeScript

Robin
Updated on November 12, 2023

To have a complete setup for your Node.js and Express server with TypeScript you need to follow 5 simple steps. This way you can create a boilerplate so that you can use it for your future project.

Here are the 5 simple steps to have the best TypeScript setup for a Node.js and Express server:

  1. Create a package.json File
  2. Installing Packages for The Project
  3. Create a tsconfig.json File and Configure TypeScript
  4. Create an Express Server Using TypeScript
  5. Add Scripts to Watch File Changes and Build Project

Let's see every step in detail

Best Setup to Use Typescript with Node.js and Express Project

Step 1: Create package.json File

First, you need to create a directory where we will keep our project files. Then inside that directory, you will create a package.json file.

          mkdir node-typescript-project
cd node-typescript-project
npm init --yes
        

I am creating a directory called node-typescript-project using mkdir command but you can name your directory whatever you like.

Then go inside your directory using the cd command.

While creating your package.json file, you can use --yes flag to get all the default settings. Otherwise, you can define your setting manually without using --yes flag.

When you open your directory in a text editor, you can check your package.json file. With the default setting it will look something like this:

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

Step 2: Installing Packages for The Project

Now we will install our necessary packages as dependencies and devDependencies for the project. We will install 2 packages as dependencies express and dotenv.

          npm install express dotenv
        

You can use the above npm command to install those packages:

We also need a few packages for the development as devDependencies. You can install them with the following command:

          npm install --save-dev nodemon ts-node typescript @types/express @types/node
        

I am installing nodemon and ts-node packages. Here, the --save-dev flag is used to tell Node that these packages are not our main dependencies for the project. These are dev dependencies.

  • nodemon - This package tracks changes in a project and restarts the server automatically. When you update any code in your Node project, it will restart your server with the updated code.
  • ts-node - It is a TypeScript execution engine for Node. It is necessary for nodemon to execute your TypeScript files on Node.js without precompiling.

You also have to install typescript and the @types declaration packages for Express and Node.js because they don't come with type declaration files.

You can open your package.json file to see the list of packages installed in your project. There you will find your packages are divided into 2 groups.

All main dependencies are inside the dependencies block and dev dependencies are indie the devDependencies block.


Step 3: Create tsconfig.json File and Configure TypeScript

Even though you have installed typescript in your project as a dev dependency, you also have to install it globally.

          npm install -g typescript
        

When you have the TypeScript package installed in your system, you can use tsc command to generate a tsconfig.json file.

It's a configuration file for TypeScript. TypeScript will use this file while compiling your project into JavaScript.

          tsc --init
        

If you don't have TypeScript installed globally on your computer, you have to add npx with the previous command to generate a tsconfig.json file.

          npx tsc --init
        

Now, it's time to configure our TypeScript settings in the tsconfig.json file for the project. TypeScript compiler will use these settings to compile your project into JavaScript.

Inside this file, there is one mandatory field called compilerOptions. These are the options you should configure in this field:

  • target - Allows us to specify the target version of JavaScript that the compiler will output.
  • module - Specifies a module manager in the compiled JavaScript code. It supports CommonJS which is standard in Node.js
  • outDir - Sets an output directory where the compiler will store all compiled JavaScript files.
  • rootDir - Specifies the root directory of input files. All TypeScript files will live inside that directory.
  • strict - If it is set to true, it enables all strict type-checking options.
  • moduleResolution - Specify module resolution strategy.
  • esModuleInterop - It allows compiling ES6 modules to CommonJS modules in Node.js
  • skipLibCheck - If it is set to true, it will skip type checking of default library declaration files.
  • forceConsistentCasingInFileNames - If it is set to true, it will enable case-sensitive file naming.

When you remove all the comments from tsconfig.json file, it will look something like this:

          {
    "compilerOptions": {
        "target": "ES2015",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    },
    "include": ["./src"]
}

        

By default, target is set to "es5" but I am setting it to "ES2015". If you want you can use any ECMAScript version.

As a rootDir, I am specifying the src directory because I will create this directory in our next step. That means I am telling the compiler that all my TypeScript files will live inside this directory.

When we set a directory as our rootDir, we have to add an additional field beside compilerOptions field which is include.

This include field is an array. Here, we also have to specify the path of our src folder. In this way, the compiler will only compile TypeScript files that are inside this directory.

Otherwise, the compiler will also try to compile any TypeScript file outside the src directory and will give an error.


Step 4: Create an Express Server Using TypeScript

After installing all of our packages, let's create a simple Express server with TypeScript. At first, I will create a directory called src inside the node-typescript-project directory that I have created in step 1.

Inside the src directory, all of our TypeScript files will live.

Let's create app.ts file in the src directory. It will be the entry point of our Node.js application. Add the following code to the app.ts file.

          import { config } from 'dotenv';
import express, { Application, NextFunction, Request, Response } from 'express';

config();

const app: Application = express();

app.get('/', (req: Request, res: Response, next: NextFunction) => {
    res.send('Express server with TypeScript');
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

        

I am using dotenv package to load environment variables from a .env file. There is a function called config() in this package. You just have to import and call this function to load environment variables in the Node.js application.

          PORT=3000

        

I have created a .env file with the above code inside the node-typescript-project directory. As we are using the dotenv package, I can access the PORT variable using process.env.PORT in our application.

Also Read: Easiest Way to Set & Use Environment Variables (.env) in Node.js


Step 5: Add Scripts to Watch File Changes and Build Project

In Node.js, scripts are the commands that are used to perform different tasks. You can add different scripts in the package.json file.

For this project, I will add 3 scripts:

  • build - It will build our project for production.
  • dev - It will run our project for development. If you update your code, it will automatically restart the server.
  • start - It will start the production server after we build our project using the build script.
            "scripts": {
    "build": "tsc",
    "dev": "nodemon ./src/app.ts",
    "start": "node ./dist/app.js"
  },

        

In the build script, you will specify tsc if you have TypeScript installed globally on your computer. Otherwise, you have to use npx tsc. It will compile our project to JavaScript and store it inside the ./dist directory. Because we specified this directory as outDir in the tsconfig.json file.

In the dev script, I am specifying the app.ts file inside the src directory. As it is a TypeScript file, nodemon package will also use the ts-node package in the background to compile it.

The start script will execute the app.js file inside the ./dist directory. We will only use this script after building our project.

  • npm run build - When you run this command in your terminal window, it will build your project.
  • npm run dev - This command will spin up a development server at http://localhost:3000. It will also restart your server when you change something in your code.
  • npm run start - It will start the production server at http://localhost:3000 after building your project.

Conclusion

You have successfully set your Node.js and Express server with TypeScript. From now on you can use it as a boilerplate for any future Node.js project.

You just have to add the necessary packages and routes for your projects. You can use any TypeScript features. It will give you type safety and all the other benefits that you get using TypeScript.

Related Posts