Setting up a backend server with TypeScript and Express.js is an excellent choice for building scalable and maintainable applications. This guide will walk you through the process step-by-step, ensuring you have a robust foundation for your project.
Table of Contents
- Introduction
- Prerequisites
- Setting Up the Project
- Configuring TypeScript
- Setting Up Express.js
- Creating a Basic Server
- Adding TypeScript Types
- Structuring the Project
- Handling Routes
- Error Handling
TypeScript is a statically typed superset of JavaScript that enhances code quality and maintainability. Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Combining TypeScript with Express.js allows you to write clean, scalable, and well-typed code for your backend server.
Prerequisites
Before we begin, ensure you have the following installed on your machine:
- Node.js (v14 or later)
- npm (v6 or later)
- TypeScript (v4 or later)
Setting Up the Project
First, create a new directory for your project and initialize it with npm.
mkdir my-backend-server
cd my-backend-server
npm init -y
Configuring TypeScript
Next, install TypeScript and the necessary type definitions.
npm install typescript ts-node @types/node --save-dev
Create a tsconfig.json
file in the root of your project with the following content:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Setting Up Express.js
Install Express.js and its type definitions.
npm install express
npm install @types/express --save-dev
Creating a Basic Server
Create a src
directory and add an index.ts
file inside it. This will be the entry point of your application.
import express, { Application, Request, Response } from 'express';
const app: Application = express();
const port: number = 3000;
app.get('/', (req: Request, res: Response) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
To run the server, add a script to your package.json:
"scripts": {
"start": "ts-node src/index.ts"
}
Then start the server:
npm start
Adding TypeScript Types
TypeScript types improve the reliability and readability of your code. You already have the types for Node.js and Express.js installed, which cover most use cases. However, if you use other libraries, make sure to install their type definitions as well.
Structuring the Project
A well-structured project improves maintainability. Here is a suggested structure:
my-backend-server/
├── src/
│ ├── controllers/
│ ├── routes/
│ ├── services/
│ ├── index.ts
├── package.json
├── tsconfig.json
Handling Routes
Create a routes
directory and add a userRoutes.ts
file for user-related routes.
import { Router, Request, Response } from 'express';
const router: Router = Router();
router.get('/users', (req: Request, res: Response) => {
res.send('Get all users');
});
export default router;
Update index.ts to use the new route:
import express, { Application } from 'express';
import userRoutes from './routes/userRoutes';
const app: Application = express();
const port: number = 3000;
app.use('/api', userRoutes);
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Error Handling
Create a middleware for handling errors. Add a middlewares
directory with an errorHandler.ts
file.
import { Request, Response, NextFunction } from 'express';
const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
res.status(500).send('Something broke!');
};
export default errorHandler;
Use this middleware in index.ts:
import express, { Application } from 'express';
import userRoutes from './routes/userRoutes';
import errorHandler from './middlewares/errorHandler';
const app: Application = express();
const port: number = 3000;
app.use('/api', userRoutes);
app.use(errorHandler);
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
You’ve successfully set up a backend server using TypeScript and Express.js. This setup ensures type safety, scalability, and maintainability for your project. As you continue to develop your application, consider adding more features, such as database integration, authentication, and more comprehensive error handling.
Top comments (0)