DEV Community

Cover image for How to Set Up a Backend Server with TypeScript and Express.js
Kafeel Ahmad (kaf shekh)
Kafeel Ahmad (kaf shekh)

Posted on

How to Set Up a Backend Server with TypeScript and Express.js

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

  1. Introduction
  2. Prerequisites
  3. Setting Up the Project
  4. Configuring TypeScript
  5. Setting Up Express.js
  6. Creating a Basic Server
  7. Adding TypeScript Types
  8. Structuring the Project
  9. Handling Routes
  10. 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
Enter fullscreen mode Exit fullscreen mode

Configuring TypeScript

Next, install TypeScript and the necessary type definitions.

npm install typescript ts-node @types/node --save-dev
Enter fullscreen mode Exit fullscreen mode

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"]
}
Enter fullscreen mode Exit fullscreen mode

Setting Up Express.js

Install Express.js and its type definitions.

npm install express
npm install @types/express --save-dev
Enter fullscreen mode Exit fullscreen mode

Creating a Basic Server
Create a srcdirectory 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}`);
});
Enter fullscreen mode Exit fullscreen mode

To run the server, add a script to your package.json:

"scripts": {
  "start": "ts-node src/index.ts"
}
Enter fullscreen mode Exit fullscreen mode

Then start the server:

npm start
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Handling Routes

Create a routesdirectory 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;
Enter fullscreen mode Exit fullscreen mode

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}`);
});

Enter fullscreen mode Exit fullscreen mode

Error Handling

Create a middleware for handling errors. Add a middlewaresdirectory 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;
Enter fullscreen mode Exit fullscreen mode

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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)