Debugging TypeScript backend service: Step-by-Step guide
Background
Node and Express.js are increasingly popular for developing backend APIs. Although building a RESTful API with Express.js is straightforward, not all developers know how to debug applications in Visual Studio Code. This article shares my insights on debugging an Express backend service, aiming to assist other developers.
Bootstrap a backend API
Before we can debug, we need a RESTful API project using Express.js. If you haven't had one yet, bootstrapped it with:
mkdir my-api && cd my-api npm init -y
npm install express dotenv cors
npm install -D typescript tsx @types/node @types/express @types/cors
npx tsc --init
This will create an RESTful api project.
Create a folder src and created two files app.ts and server.ts.
my-api/
|-- src/
| |-- app.ts
| |-- server.ts
Setup a GET endpoint / in app.ts returning a json that indicates the API is running.
import express from 'express';
import type { Application, Request, Response } from 'express';
import cors from 'cors';
const app: Application = express();
app.use(cors());
app.use(express.json());
app.get('/', (req: Request, res: Response) => {
res.status(200).json({ message: 'API is running smoothly' });
});
export default app;
The src/server.ts specifies the application to listen to port 3000.
import app from './app';
const PORT = 3000;
app.listen(PORT, () => {
console.log(`🚀 Server ready at: http://localhost:${PORT}`);
});
In package.json, add the scripts to develop, build and start the application.
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
}
The above config will allow you to run npm run dev to start the application.
Create vscode/launch.json
Create vscode/launch.json with the following content:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Backend",
"request": "launch",
"skipFiles": ["<node_internals>/**"],
"type": "node",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"]
}
]
}
This config tells VS Code to attach the debugger once your application is started by
npm run dev.