[Express.js] Setting Up an Express.js API with TypeScript from Scratch

Leisure Rife
3 min readMay 29, 2024

--

Canva

Express.js Series Articles

  1. (current)Setting Up an Express.js API with TypeScript from Scratch
  2. Setting Up Coding Conventions and Transpiling TypeScript into JavaScript
  3. Adding Debug Configuration and Starting the Debugger with VSCode
  4. (To be updated)

Preface

I am building an API template using Express.js and TypeScript to streamline future development projects. This article is part of a series documenting my progress, helping me deepen my understanding. Your feedback and suggestions are welcome.

This article is about how to start your Express.js project.

Prerequisite

Ensure you have Node.js and npm installed. If you use macOS, I recommend using nvm (Node Version Manager) for managing Node.js versions efficiently.

## MacOS Version: Sonoma 14.3.1
## Below is my nvm and node version
% nvm -v
0.39.3
% node -v
v19.1.0
% npm -v
8.19.3

You can find installation instructions for nvm, Node.js, and npm online.

Step 1 Create a Folder for the API

% mkdir myapi
% cd myapi

Step2 add .gitignore

Create a .gitignore file in the root folder to exclude node-specific files. You can refer to these resources as below.

Step3 Initialize package.json

Run the following command with -y to create a package.json file with skiping the questionnaire altogether and using default values.

myapi% npm init -y

Step4 Install Necessary Packages

Install Express:

myapi% npm i express

Install TypeScript and type definitions for Express as development dependencies:

myapi% npm i -D typescript @types/express

Note: npm i is shorthand for npm install.

Step5 Initialize tsconfig.json

Create a TypeScript configuration file:

myapi% npx tsc --init

Step6 Add start file

Create an app.ts file for starting the server:

import express, { Express } from "express"

const app: Express = express()
const port: number = 3000

app.get('/', (req, res) => {
res.send('Hello World!')
})

app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

Step6 Execute

Start the server and listen on port 3000 for connections using:

myapi% npx ts-node app.ts

You should see the message:

Example app listening on port 3000

Step7 Check the Result in the Browser

Open your browser and navigate to http://localhost:3000. You should see "Hello World!" displayed.

localhost:3000

Conclusion

This is the first step in setting up an Express.js API with TypeScript. Future articles will cover topics such as hot-reloading, debugging, coding standards (eslint), relative paths, and transpiling TypeScript files to JavaScript. Stay tuned for more updates!

You can find the Express.js source code at the link below.

https://github.com/FlyRayTsou/expressjs-api-template/tree/v0.0.1

Reference

--

--

Leisure Rife

尋找著在忙忙碌碌的世界中,最適合自己的生活,也或許不斷的移動城市是我的生活方式