Complete guide for setting up a TypeScript project with Express:
-
Create a new directory for your project and navigate to it:
mkdir express-typescript-project cd express-typescript-project
-
Initialize a new Node.js project:
npm init -y
-
Install Express and related dependencies:
npm install express body-parser cors
-
Install TypeScript and its type definitions:
npm install --save-dev typescript @types/node @types/express
-
Optional utilities:
npm install dotenv npm install --save-dev ts-node nodemon
-
Initialize a TypeScript configuration file:
npx tsc --init
-
Update
tsconfig.json
for a Node.js + Express setup:{ "compilerOptions": { "target": "ES2020", "module": "CommonJS", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] }
Create the following folders and files:
.
├── src
│ ├── app.ts
│ ├── routes
│ │ └── index.ts
│ ├── controllers
│ │ └── home.controller.ts
│ ├── middlewares
│ │ └── logger.middleware.ts
│ └── config
│ └── index.ts
├── tsconfig.json
├── package.json
├── .env
├── .gitignore
└── nodemon.json
PORT=3000
import express, { Application } from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { config } from 'dotenv';
import routes from './routes';
config(); // Load environment variables
const app: Application = express();
// Middlewares
app.use(bodyParser.json());
app.use(cors());
// Routes
app.use('/api', routes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
import { Router } from 'express';
import { getHome } from '../controllers/home.controller';
const router = Router();
router.get('/', getHome);
export default router;
import { Request, Response } from 'express';
export const getHome = (req: Request, res: Response) => {
res.json({ message: 'Welcome to Express with TypeScript!' });
};
import { Request, Response, NextFunction } from 'express';
export const logger = (req: Request, res: Response, next: NextFunction) => {
console.log(`${req.method} ${req.url}`);
next();
};
import { config } from 'dotenv';
config();
export const PORT = process.env.PORT || 3000;
"scripts": {
"start": "node dist/app.js",
"dev": "nodemon src/app.ts",
"build": "tsc",
"test": "echo \"No tests specified\" && exit 1"
}
{
"watch": ["src"],
"ext": "ts",
"ignore": ["dist"],
"exec": "ts-node ./src/app.ts"
}
-
Start the development server:
npm run dev
-
Open your browser or Postman and navigate to:
http://localhost:3000/api
You should see:
{ "message": "Welcome to Express with TypeScript!" }
To compile the TypeScript code to JavaScript and run it:
npm run build
npm start
-
Error Handling Middleware:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send({ error: 'Something broke!' }); });
-
TypeScript Linting:
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
-
API Documentation: Use
swagger-jsdoc
andswagger-ui-express
. -
Testing: Use
jest
andsupertest
for unit and integration tests.
video: https://youtu.be/zRo2tvQpus8 Article: https://www.typescripttutorial.net/typescript-express/setup-express-with-typescript/