0d29ff67-9bc6-4d66-a4cb-b34692ba9f46 Skip to content

How to Build a REST API with Node.js and Express

Node.js Express.js

Introduction

A REST API allows applications to communicate over the internet using standard HTTP methods. This guide explains how to create a REST API using Node.js, Express, and TypeScript.

By the end of this guide, you’ll have a fully functional REST API that supports CRUD operations (Create, Read, Update, Delete).


Prerequisites

Ensure you have the following installed:

How to Install Node.js

  1. Visit the Node.js download page.
  2. Download the LTS (Long-Term Support) version and run the installer.
  3. Verify your installation:
    Terminal window
    node -v # Check node version
    npm -v # Check npm version

Step 1: Set Up a New Node.js Project

Create a new project folder and initialize a Node.js project:

Terminal window
mkdir rest-api-nodejs
cd rest-api-nodejs
npm init -y

Understanding package.json

The command above generates a package.json file, which stores project metadata and dependencies. Open package.json in a text editor for further configuration.

Learn more about package.json in the official documentation.


Step 2: Install Dependencies and Set Up TypeScript

Install express and nodemon:

Terminal window
npm install express
npm install --save-dev nodemon

Install TypeScript along with necessary type definitions:

Terminal window
npm install --save-dev typescript ts-node @types/node @types/express

Create tsconfig.json

Now, we will create a configuration for TypeScript:

tsconfig.json
{ "compilerOptions": { "outDir": "./dist", "rootDir": "./src", "strict": true } }

Create the src directory:

Terminal window
mkdir src

Step 3: Create the Express Server

Create an index.ts file in the src directory. This will be the root of our Node.js application. We’ve heavily commented the code to help you understand each part:

src/index.ts
// Import the express.js library as 'express'
import express from 'express';
// Construct a new express application (on the 'app' variable)
const app = express();
// Determine the port we want to listen on. This code means:
// - read the 'PORT' defined in the environment variables
// - if not found, default to 5000
const PORT = process.env.PORT || 5000;
// Allow express.js to process JSON input
app.use(express.json());
// Define a GET route for the root URL ('/')
app.get('/', (req, res) => {
// Send a response to the client
res.send({ hello: "Welcome to the REST API built with TypeScript and Express.js!" });
});
// Start the server on the port determined above
app.listen(PORT, () => {
// This function is called once the server is available
console.log(`Server running on port ${PORT}`);
});

Step 4: Define API Routes (CRUD Operations in Node.js)

In src/index.ts, add your API routes:

const books = [
{ id: 1, title: 'The Pragmatic Programmer', author: 'Andy Hunt' },
{ id: 2, title: 'Clean Code', author: 'Robert C. Martin' },
];
app.get('/books', (req, res) => {
res.json(books);
});

Step 7: Deploying the API

Deploying to Heroku

Terminal window
heroku create
git push heroku main
heroku open

Deploying to Vercel

  1. Create a free account on Vercel: Sign Up
  2. Install the Vercel CLI:
    Terminal window
    npm install -g vercel
  3. Deploy your application:
    Terminal window
    vercel

Deploying to DigitalOcean

  1. Create an account on DigitalOcean: Sign Up with $100 Credit
  2. Create a Droplet.
  3. SSH into your server:
    Terminal window
    ssh root@your-droplet-ip
  4. Install Docker:
    Terminal window
    apt update && apt install docker.io
  5. Clone your repository and run your API within a Docker container:
    Terminal window
    git clone your-repo.git
    cd your-repo
    docker build -t my-api .
    docker run -p 5000:5000 my-api

Step 8: Add Authentication (Securing the API)

This section describes how to secure your API using JWT and cookies.

Using API Tokens (JWT) in an Express API

Install the required dependencies:

Terminal window
npm install jsonwebtoken dotenv

Generate a token:

import jwt from 'jsonwebtoken';
const generateToken = (userId: string) => {
return jwt.sign({ userId }, process.env.JWT_SECRET as string, { expiresIn: '1h' });
};

Secure routes with JWT authentication:

const authenticate = (req: any, res: any, next: any) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Unauthorized' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
req.user = decoded;
next();
} catch {
res.status(403).json({ message: 'Invalid token' });
}
};

Using Cookies for Authentication

Install cookie-parser:

Terminal window
npm install cookie-parser

Set and retrieve cookies for authentication:

import cookieParser from 'cookie-parser';
app.use(cookieParser());
app.post('/login', (req, res) => {
const token = generateToken('user123');
res.cookie('auth_token', token, { httpOnly: true });
res.json({ message: 'Logged in!' });
});
app.get('/protected', (req, res) => {
const token = req.cookies.auth_token;
if (!token) return res.status(401).json({ message: 'Unauthorized' });
res.json({ message: 'You are authenticated!' });
});

Conclusion

This guide provided a detailed walkthrough for building a REST API with Node.js and Express, adding authentication using JWT and cookies, and deploying your API to Heroku, Vercel, and DigitalOcean.

Next steps include connecting the API to a database (such as MongoDB or PostgreSQL), improving security with rate limiting and HTTPS, implementing caching for better performance, and scaling your API using cloud services.