How to use TypeScript to build Node.js API with Express ?
Last Updated :
26 Jul, 2024
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will walk you through the 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.
Similar Reads
How to use express in typescript ?
In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nod
2 min read
How to Update value with put in Express/Node JS?
Express JS provides various HTTP methods to interact with data. Among these methods, the PUT method is commonly used to update existing resources. PrerequisitesNode JS Express JS In this article, we are going to setup the request endpoint on the server side using Express JS and Node JS. This endpoin
2 min read
How to use Typescript with native ES6 Promises ?
What is TypeScript? TypeScript is a free as well as an open-source programming language which was developed and is maintained by Microsoft. It actually provides highly productive development tools for JavaScript IDEs and also for practices like static checking. It even makes code easier to read and
3 min read
How to use TypeScript with React?
TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
3 min read
How to Use MathJS with TypeScript?
Math.js library can be use with TypeScript to handle various mathematical tasks while getting the benefits of TypeScriptâs type safety and autocompletion. Integrating Math.js into your TypeScript project allows you to perform arithmetic, algebra, statistics, and more, with the added advantage of Typ
3 min read
How to use jQuery with TypeScript ?
In this article, we will learn how we can use jQuery with TypeScript and implement the features of both languages. The below approach can be used to implement jQuery in TypeScript. By installing jQuery using the npm commandThe jQuery can be installed in your current TypeScript project folder using t
2 min read
How to Make Next.js getStaticProps Work With Typescript?
Next.js is a popular React framework that developers use to create efficient server-rendered and static applications. One of the key features is to fetch data at build time, using a function called getStaticProps. This function enables developers to make static pages that are served fast to users, t
5 min read
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
How to Test TypeScript with Jest?
Jest, a powerful JavaScript testing framework, seamlessly integrates with TypeScript, providing all the tools needed to write and run tests for your TypeScript code, ensuring quality and reliability. It handles TypeScript compilation automatically, offers features like mocking and code coverage, and
3 min read
How to use Async/Await with a Promise in TypeScript ?
In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable. What is a Promise?A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be ava
3 min read