How to use TypeScript to build Node.js API with Express ?

TypeScript is a powerful superset of JavaScript that adds static typing and other features, making it easier to build and maintain large-scale applications. When combined with Node.js and Express, TypeScript can enhance your development experience by providing type safety and better tooling. This guide will walk you through building a Node.js API using Express and TypeScript.

Prerequisites:

Approach

  • Create folders for the source code (src), configuration files, and test files.
  • Initialize a new Node.js project and install Express, TypeScript, and necessary type definitions.
  • Implement two fake API endpoints in the src folder – one for creating a user and another for getting user data.
  • Set up TypeScript configuration with tsconfig.json to compile TypeScript files to JavaScript.
  • Use Postman to test the API endpoints and verify the responses.

Setting Up the Project

Step 1: Initialize the Project

Create a new directory for your project and initialize a new Node.js project:

mkdir express-typescript-api
cd express-typescript-api
npm init -y

Step 2: Install Dependencies

Install Express and its types, as well as TypeScript and necessary development dependencies:

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

Step 3: Configure TypeScript

Create a tsconfig.json file to configure the TypeScript compiler

{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}

Steps to Use

Step 1: If you are set up the project in the use of the above article your directory looks like this.

Step 2: Open the index.ts file and write the below code. First of all, create an ExpressJs code in TypeScript and flow the good practices.

Javascript
//index.js

// Import the express with express name
import express from 'express';

// Initialize the express module with app variable
const app: express.Application = express();

// Define the port for the application is run
const port: number = 3000;

// Handle the coming data.
app.use(express.json());

// Handle '/', path of the api.
app.get('/', (_req, _res): void => {
    _res.json({
        'name': 'typescitp_api',
        'path': '/',
        'work': 'search_other_apis'
    });
});


// Server the api endpoints.
app.listen(port, (): void => {
    console.log(`Typescript API server http://localhost:${port}/`);
});

 
Step 3: In this step, we create two API endpoints for creating the user and getting the users’ data. Firstly create a global array to treat as a fake database.

let fake_db: any = [];

Then create a first API endpoint to create the users and store the user data in the fake database. We are working with API endpoint so data are passed through the post method or JSON data format. In the below code, we firstly handle a post request and create a  ‘/create’ route the manage or create user API endpoint and after that assign the coming body data to our fake database and return appropriate output.

Javascript
// index.js
// Handle '/create', path for create user
app.post('/create', (_req, _res): void => {

    // Fetched the user using body data
    const user: object = _req.body;

    // Assign the user in fake_db with id as a index
    fake_db.push(user);

    _res.json({
        "success": true,
        "data": user
    });
});

After writing all codes lets, move to the test phase and look at what our API makes output.

Step 5: Now the final step is to test all the created routes using Postman. If you don’t know about the postman refer to this article.

Test ‘/’ root path using postman

The root path working properly, so we are moving to another API endpoint.

Test ‘/create’ path in post request using postman.

We pass raw JSON data directly.

Test ‘/users’ path using postman.

Conclusion

By following this guide, you have set up a basic Node.js API using Express and TypeScript. This setup provides a strong foundation for building scalable and maintainable server-side applications with type safety and better tooling. You can expand this project by adding more routes, controllers, and models, as well as integrating databases and other services.