This guide will walk you through setting up an Express.js server using TypeScript. The setup includes TypeScript configuration, development dependencies, and scripts for building and running the server.
Make sure you have Node.js installed.
Create a new project folder, navigate into it, and initialize it with npm init.
mkdir my-express-ts-server
cd my-express-ts-server
npm init -yInstall Express, TypeScript, and types for Node.js and Express. We’ll also install ts-node and nodemon for easier development with TypeScript.
npm install express typescript @types/node @types/express ts-node nodemonInitialize TypeScript configuration with:
npx tsc --initThis will create a tsconfig.json file. Here are some suggested modifications to enable better compatibility for Node.js and Express:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}rootDir: Specifies the root directory of our source files.outDir: Specifies the output directory for compiled files.
Create the following project structure:
my-express-ts-server/
├── src/
│ └── index.ts
├── tsconfig.json
├── package.json
└── README.md
In src/index.ts, set up a basic Express server:
import express, { Request, Response } from "express";
const app = express();
const PORT = process.env.PORT || 5000;
app.get("/", (req: Request, res: Response) => {
res.send("Hello, TypeScript with Express!");
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});Add the following scripts to simplify building and running the server:
"scripts": {
"build": "tsc",
"start": "npm run build && node ./dist/index.js",
"dev": "nodemon --exec ts-node src/index.ts"
}build: Compiles the TypeScript code into JavaScript in thedistfolder.start: Runs thebuildscript, then starts the compiled server with Node.js.dev: Usesnodemonandts-nodeto run the server in development mode with auto-reloading.
For development with live reloading:
npm run devFor production (after compiling TypeScript files):
npm startOnce the server is running, open a browser or use a tool like curl or Postman to visit http://localhost:3000. You should see the message:
Hello, TypeScript with Express!