DEV Community

Cover image for Mastering Express: Building Robust TypeScript Servers with Ease.
Kunal Agrawal
Kunal Agrawal

Posted on • Updated on

Mastering Express: Building Robust TypeScript Servers with Ease.

This article is a step by step tutorial to create a express server using typescript.

Note: Typescript cannot be run directly into node runtime environment, although runtime like Deno, Bun supports typescript.

Create a folder, initialize npm package using:

npm init --y
Enter fullscreen mode Exit fullscreen mode

Let's install dependencies required to create express server.
express, @types/express to use type definitions, intellisense in code editor. Also few developer dependencies like typescript to convert typescript file into javascript file, nodemon to ease our development (it automatically watch for changes, and reload your code in runtime), concurrently to run both the above developer dependencies simultaneously.

npm i express @types/express && npm i -d nodemon concurrently
Enter fullscreen mode Exit fullscreen mode

Let's initialize typescript in the project. using the following command

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

A tsconfig.json file will be created in the project. In the tsconfig.json file uncomment outDir line and enter a outDir (dist here):

"outDir": "./dist"
Enter fullscreen mode Exit fullscreen mode

Let's create a NPM script for this typescript express configuration.

In pacakage.json file add following code,

"dev" : "concurrently \" tsc --watch\" \"nodemon dist/index.js\""
Enter fullscreen mode Exit fullscreen mode

also remove a line

"main" : "index.js"
Enter fullscreen mode Exit fullscreen mode

now the final part, create index.ts file.

import express from "express";
const PORT = 3000;
const app = express();
app.get("/",(req,res)=>{
  res.send("Hello");
}
app.listen(PORT);
Enter fullscreen mode Exit fullscreen mode

Run the dev script you just created in command line using:

npm run dev
Enter fullscreen mode Exit fullscreen mode

That's it you're good to go, your express typescript server is ready at localhost, port 3000 Link

Let's Connect -
Tweet Thanks
LinkTree

Top comments (0)