How to Build a REST API with Node.js and Express
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:
Node.js
(Download from the official site)npm
(Node Package Manager) (Included withNode.js
)- A code editor (VS Code recommended)
How to Install Node.js
- Visit the Node.js download page.
- Download the LTS (Long-Term Support) version and run the installer.
- Verify your installation:
Terminal window node -v # Check node versionnpm -v # Check npm version
Step 1: Set Up a New Node.js
Project
Create a new project folder and initialize a Node.js
project:
mkdir rest-api-nodejscd rest-api-nodejsnpm 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
:
npm install expressnpm install --save-dev nodemon
Install TypeScript
along with necessary type definitions:
npm install --save-dev typescript ts-node @types/node @types/express
Create tsconfig.json
Now, we will create a configuration for TypeScript:
{ "compilerOptions": { "outDir": "./dist", "rootDir": "./src", "strict": true } }
Create the src
directory:
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:
// 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 5000const PORT = process.env.PORT || 5000;
// Allow express.js to process JSON inputapp.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 aboveapp.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
heroku creategit push heroku mainheroku open
Deploying to Vercel
- Create a free account on Vercel: Sign Up
- Install the
Vercel
CLI:Terminal window npm install -g vercel - Deploy your application:
Terminal window vercel
Deploying to DigitalOcean
- Create an account on DigitalOcean: Sign Up with $100 Credit
- Create a Droplet.
- SSH into your server:
Terminal window ssh root@your-droplet-ip - Install Docker:
Terminal window apt update && apt install docker.io - Clone your repository and run your API within a Docker container:
Terminal window git clone your-repo.gitcd your-repodocker 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:
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
:
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.