🔍
Artificial Intelligence Cybersecurity Windows Mac Android iPhone Software How-To Guides Reviews Comparisons Productivity Internet Apps Cloud Business Software About Contact

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

Building a REST API with Node.js and Express is a fundamental skill for modern web developers. This guide walks through creating a complete API from scratch.

Setting Up the Project

Create a new directory and run npm init -y. Install Express: npm install express. Install nodemon for development: npm install -D nodemon. Create an index.js file. Set up a basic Express server: const express = require('express'); const app = express(); app.listen(3000).

Defining Routes

Create routes for CRUD operations: app.get('/api/items') for reading, app.post('/api/items') for creating, app.put('/api/items/:id') for updating, and app.delete('/api/items/:id') for deleting. Use express.Router() to organize routes into separate files. Always use plural nouns for resource names.

Adding Middleware

Use app.use(express.json()) to parse JSON bodies. Add CORS with the cors package: app.use(cors()). Create custom middleware for logging, authentication, and error handling. Middleware runs in the order it is defined. Always define error-handling middleware last with four parameters (err, req, res, next).

Connecting a Database

For simplicity, start with SQLite using better-sqlite3 or Prisma. For production, use PostgreSQL. Install Prisma: npm install prisma @prisma/client. Run npx prisma init and define your schema. Use Prisma Client to query the database: prisma.item.findMany(). Always use parameterized queries to prevent SQL injection.

Adding Authentication

Implement JWT (JSON Web Token) authentication. Install jsonwebtoken and bcrypt. Hash passwords before storing. Issue JWT tokens on login. Create auth middleware that verifies tokens on protected routes. Store secrets in environment variables. Use refresh tokens for better security.

Deploying Your API

Deploy on Render, Railway, or Fly.io for simple hosting. Use environment variables for configuration. Set up a process manager like PM2 for production. Add rate limiting with express-rate-limit. Enable HTTPS. Add input validation with Joi or Zod. Write tests with Jest and Supertest.