“Learn how to build a REST API with Node.js and Express.js using MongoDB, CRUD routes, middleware, validation, error handling, JWT authentication, Postman testing, and production-ready practices in one clear, step-by-step guide for new backend developers.”
Most people never see the API behind an app, yet it quietly powers almost everything they do. Users never see it, yet every login, saved note, and payment depends on it. If you want a Node.js REST API tutorial that goes beyond one file and three routes, this Express.js REST API tutorial is for you. We will build a small task manager API with a real folder structure, a database, validation, error handling, and login.
I wrote this the way I set up client projects. I start with a clear structure, add one feature at a time, and test each step before moving on. By the end, you will know how to build a REST API using Node.js and Express.js that is ready to grow, and you will understand why each piece exists. If Node.js is still new to you, read what Node.js is first. A quick read now will save you confusion later in the steps below. Teams that need help shipping a production API can also look at backend development services.
48.7%
of respondents used Node.js in the 2025 Stack Overflow Developer
19.9%
of respondents used Express in the same survey
What Is a REST API, and Where Does Express.js Fit In?
What Is a REST API in Node.js?
A REST API is a way for two programs to talk over HTTP using clear URLs and standard methods. A client asks for a resource, such as a task or a user. The server replies with data, usually JSON, plus a status code that says what happened. Each request carries all the details the server needs, so the server does not remember the client between calls.
REST works well because it is predictable. A URL such as /api/v1/tasks always points to the task collection, and the HTTP method tells the server what to do. If you are unsure whether REST is the right style for your project, the guide on REST vs GraphQL compares both. For most CRUD apps, a RESTful API in Node.js is the simpler path.
What Is Express.js, and Why Is It Popular for Node.js Backend Development?
Express.js is a lightweight framework that runs on top of Node.js and makes handling web requests much easier. It gives you routing, middleware, and helpers for requests and responses, and it does not force a fixed project layout. That freedom is why Express still sits behind a large share of Node.js backend development. Express 5 is the current major version, and it needs Node.js 18 or newer.
Because Express runs on Node.js, it also helps to understand how Node.js works internally, especially how it handles many requests at once.
Express is a good fit when you want control over every layer. If you prefer a framework with more built-in structure, the comparison of NestJS vs Express.js can help you choose. This guide uses Express because it teaches the core ideas that other frameworks build on.
Build REST API with Node.js and Express.js: Project Setup
Prerequisites for a Node.js REST API Project for Beginners
You need only a few tools to follow along. Check that each item below is ready before you create the project folder.
- A current LTS version of Node.js (22 or 24 is a safe choice) with npm
- A MongoDB database, either a free MongoDB Atlas cluster or a local install
- Postman or any other API client for testing
- A code editor such as VS Code
- Basic JavaScript knowledge, including async and await
This Node.js REST API project for beginners assumes you can read basic JavaScript. You do not need to know Express yet, so treat it as an Express.js tutorial for beginners that still follows real project habits.
Create a REST API from Scratch in Node.js: Install and Configure
Start with an empty folder and install only the packages you need. Express handles HTTP, Mongoose models the data, jsonwebtoken and bcryptjs cover login, and zod checks input. The last three, helmet, cors, and morgan, add security headers, cross-origin rules, and request logs. Fewer packages also mean fewer updates to track and fewer places for security problems to hide.
mkdir node-rest-api && cd node-rest-api npm init -y npm install express mongoose jsonwebtoken bcryptjs zod helmet cors morganOpen package.json, set the module type so you can use modern import syntax, and add two scripts. The dev script restarts the server when files change and loads your .env file, with no extra package needed on Node.js 20.6 or newer.
{"name": "node-rest-api","version": "1.0.0","type": "module","scripts": {"dev": "node --watch --env-file=.env src/server.js","start": "node src/server.js"}}PORT=3000 MONGODB_URI=mongodb://127.0.0.1:27017/node_rest_api JWT_SECRET=replace-with-a-long-random-string CLIENT_URL=http://localhost:5173Add .env to your .gitignore right now. A leaked secret is much harder to fix than a missing one.
How to Structure a Node.js REST API Project: Folders That Scale
Most tutorials put everything in one file. That works for a demo, but it falls apart on the first real feature. I split code by job: routes pick the URL, controllers run the logic, models talk to the database, and middleware handles shared checks. Each folder has one reason to change, which keeps pull requests small and bugs easy to find.

Create the Server and Express.js Routing
How to Create API Routes in Express.js
Express.js routing connects an HTTP method and a URL to a handler function. Now you can create REST API using Express.js routes that group related endpoints under one prefix. In app.js, I register security middleware first, then the JSON parser, then the routes. The 404 handler and the error handler go last, because Express runs middleware in the order you write it.
import express from "express";import helmet from "helmet";import cors from "cors";import morgan from "morgan";import authRoutes from "./routes/auth.routes.js";import taskRoutes from "./routes/task.routes.js";import { notFound, errorHandler } from "./middleware/errorHandler.js"; const app = express(); app.use(helmet());app.use(cors({ origin: process.env.CLIENT_URL }));app.use(morgan("dev"));app.use(express.json({ limit: "10kb" })); app.get("/health", (req, res) => res.json({ status: "ok" }));app.use("/api/v1/auth", authRoutes);app.use("/api/v1/tasks", taskRoutes); app.use(notFound);app.use(errorHandler); export default app;Two small habits matter here. The /api/v1 prefix lets you ship a breaking change later as v2 without hurting old clients. The /health route gives hosting platforms a cheap way to check that your app is alive. I also keep server.js separate, so tests can import the app without opening a real port.
import app from "./app.js";import { connectDB } from "./config/db.js"; const port = process.env.PORT || 3000; await connectDB(process.env.MONGODB_URI);app.listen(port, () => console.log(`API running on port ${port}`));Connect MongoDB with Express.js Using Mongoose
How to Connect MongoDB with Express.js REST API
MongoDB with Node.js and Express is a popular pairing because JSON-like documents map well to JavaScript objects. The driver layer is handled by Mongoose, which adds schemas, validation, and helpful query methods. I connect to the database before the server starts listening. If the connection fails, the app stops with a clear error instead of accepting requests it cannot serve.
import mongoose from "mongoose"; export async function connectDB(uri) { await mongoose.connect(uri); console.log("MongoDB connected");}Mongoose in Node.js: Define the Task Model
Mongoose in Node.js lets you describe your data once and reuse that rule everywhere. The task schema below trims the title, caps its length, and links every task to an owner. I also add an index on owner and createdAt, because the list route always filters by owner and sorts by date. Without an index, that query slows down as the collection grows.
import mongoose from "mongoose"; const taskSchema = new mongoose.Schema( { title: { type: String, required: true, trim: true, maxlength: 120 }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }, }, { timestamps: true }); taskSchema.index({ owner: 1, createdAt: -1 }); export default mongoose.model("Task", taskSchema);MongoDB, Express, and Node.js are three of the four parts of the MERN stack. If you plan to pair this API with a React front end, see how MERN stack development fits together. You can also browse the tools I use with this stack on the skills page.
Build CRUD Operations in Node.js
HTTP Methods in REST API: GET POST PUT DELETE Requests
The table below maps each HTTP method to a task route, its purpose, and the status code a client should expect on success.
| Method | Route | Action | Success status |
|---|---|---|---|
| GET | /api/v1/tasks | List the signed-in user's tasks | 200 |
| POST | /api/v1/tasks | Create a task | 201 |
| GET | /api/v1/tasks/:id | Read one task | 200 |
| PUT | /api/v1/tasks/:id | Update a task | 200 |
| DELETE | /api/v1/tasks/:id | Delete a task | 204 |
These GET POST PUT DELETE requests cover the full life of a resource. In strict REST, PUT replaces a whole resource and PATCH changes part of it. Many teams still use PUT for updates, and the PUT route in this guide accepts partial fields to keep the code short. If you want stricter behavior, add a separate PATCH route.
How to Create CRUD API in Express.js
CRUD operations in Node.js are easy to write and easy to get wrong. The most common mistake is loading a record by id alone, which lets one user read or edit another user's data. Every query below filters by owner too. The list route also caps the page size, so a client cannot ask for ten thousand records at once.
import Task from "../models/Task.js";import { AppError } from "../middleware/errorHandler.js"; export async function listTasks(req, res) { const page = Math.max(Number(req.query.page) || 1, 1); const limit = Math.min(Number(req.query.limit) || 10, 50); const tasks = await Task.find({ owner: req.user.id }) .sort({ createdAt: -1 }) .skip((page - 1) * limit) .limit(limit); res.json({ page, limit, data: tasks });} export async function createTask(req, res) { const task = await Task.create({ ...req.body, owner: req.user.id }); res.status(201).json({ data: task });} export async function getTask(req, res) { const task = await Task.findOne({ _id: req.params.id, owner: req.user.id }); if (!task) throw new AppError("Task not found", 404); res.json({ data: task });} export async function updateTask(req, res) { const task = await Task.findOneAndUpdate( { _id: req.params.id, owner: req.user.id }, req.body, { new: true, runValidators: true } ); if (!task) throw new AppError("Task not found", 404); res.json({ data: task });} export async function deleteTask(req, res) { const task = await Task.findOneAndDelete({ _id: req.params.id, owner: req.user.id }); if (!task) throw new AppError("Task not found", 404); res.status(204).send();}Notice that these handlers have no try/catch. In Express 5, a thrown error or rejected promise goes straight to the error handler. For a larger example of an API-focused build, the social media backend API project shows how this pattern scales across many endpoints.
Express Middleware: Share Logic Once
Express middleware is a function that runs between the incoming request and your final handler. It can read the request, change it, end the response, or pass control on with next(). Your app already uses several: helmet, cors, morgan, and express.json(). Good middleware does one job and does it well, which makes it easy to reuse on any route.
REST API Request Validation with Zod
Never trust data from a client. Mongoose checks values when you save, but by then bad input is already deep inside your code. I validate at the edge, right after the body is parsed. Apps that store money values, such as the personal expense tracker project, need strict checks on every amount, date, and category.
export const validate = (schema) => (req, res, next) => { const result = schema.safeParse(req.body); if (!result.success) { return res.status(400).json({ error: "Validation failed", details: result.error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message, })), }); } req.body = result.data; next();};The last two lines are the highest priority. By replacing req.body with the parsed result, unknown fields are stripped. A client can no longer sneak in an owner value of their own. Here is the task router that wires validation, authentication, and the controller together.
import { Router } from "express";import { z } from "zod";import * as tasks from "../controllers/task.controller.js";import { requireAuth } from "../middleware/auth.js";import { validate } from "../middleware/validate.js"; const taskSchema = z.object({ title: z.string().trim().min(1).max(120), completed: z.boolean().optional(),}); const router = Router();router.use(requireAuth); router.route("/").get(tasks.listTasks).post(validate(taskSchema), tasks.createTask);router .route("/:id") .get(tasks.getTask) .put(validate(taskSchema.partial()), tasks.updateTask) .delete(tasks.deleteTask); export default router;Express Error Handling for a Reliable API
How to Handle Errors in Express.js API
Express error handling relies on one middleware with four arguments, placed after all your routes. Without it, users see raw stack traces or inconsistent responses. I use a small AppError class for expected problems, such as a missing task. The handler also maps common database errors to the right status code.
export class AppError extends Error { constructor(message, statusCode = 500) { super(message); this.statusCode = statusCode; }} export function notFound(req, res) { res.status(404).json({ error: `Route ${req.method} ${req.originalUrl} not found` });} export function errorHandler(err, req, res, next) { let status = err.statusCode || err.status || 500; let message = err.message; if (err.name === "CastError") { status = 400; message = "Invalid ID format"; } if (err.code === 11000) { status = 409; message = "That value already exists"; } if (status >= 500) { console.error(err); message = "Something went wrong"; } res.status(status).json({ error: message });}The key rule is to log the real error on the server and send a safe message to the client. Users should never see database details or file paths. Every failure also uses the same JSON shape, so front-end code can handle errors in one place.
API Authentication Using JWT
How to Implement JWT Authentication in Node.js
API authentication using JWT works like a signed ticket. After login, the server issues a token that holds the user's id. The client sends that token with each request, and the server checks the signature instead of looking up a session. The flow has three parts: hash the password at signup, compare it at login, and verify the token on protected routes. Apps with user accounts, like the real-time chat application project, need this identity layer before anything else.
import mongoose from "mongoose"; const userSchema = new mongoose.Schema( { email: { type: String, required: true, unique: true, lowercase: true, trim: true }, passwordHash: { type: String, required: true }, }, { timestamps: true }); export default mongoose.model("User", userSchema);import { Router } from "express";import bcrypt from "bcryptjs";import jwt from "jsonwebtoken";import { z } from "zod";import User from "../models/User.js";import { AppError } from "../middleware/errorHandler.js";import { validate } from "../middleware/validate.js"; const router = Router(); const credentials = z.object({ email: z.string().trim().toLowerCase().email(), password: z.string().min(8).max(72),}); const signToken = (user) => jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: "1h" }); router.post("/register", validate(credentials), async (req, res) => { const passwordHash = await bcrypt.hash(req.body.password, 12); const user = await User.create({ email: req.body.email, passwordHash }); res.status(201).json({ token: signToken(user) });}); router.post("/login", validate(credentials), async (req, res) => { const user = await User.findOne({ email: req.body.email }); const valid = user && (await bcrypt.compare(req.body.password, user.passwordHash)); if (!valid) throw new AppError("Invalid email or password", 401); res.json({ token: signToken(user) });}); export default router;import jwt from "jsonwebtoken";import { AppError } from "./errorHandler.js"; export function requireAuth(req, res, next) { const [scheme, token] = (req.headers.authorization || "").split(" "); if (scheme !== "Bearer" || !token) { throw new AppError("Authentication required", 401); } try { const payload = jwt.verify(token, process.env.JWT_SECRET); req.user = { id: payload.id }; } catch { throw new AppError("Invalid or expired token", 401); } next();}A few details are worth knowing. The password limit of 72 matches a bcrypt rule, since it only reads the first 72 bytes. The login route returns one message for both a wrong email and a wrong password, so attackers cannot learn which emails exist. If your API will serve a web app, full stack development work usually ties the front end to this same token flow.
Test REST API Using Postman
How to Test Express.js REST API Using Postman
Follow these steps in order. Each one tests a different layer of the API, from the server health check to protected routes.
- Run npm run dev, then send GET http://localhost:3000/health. You should get status 200 and {"status":"ok"}.
- Send POST /api/v1/auth/register with an email and password in a JSON body, and copy the token from the response.
- Open the Authorization tab in Postman, choose Bearer Token, and paste the token. Saving it as a collection variable saves time later.
- Send POST /api/v1/tasks with a title. Expect status 201 and the new task in the response.
- Call the list, update, and delete routes. Expect 200, 200, and 204.
- Send an empty title, then send a request with no token. Expect 400 and 401.

Once the manual checks pass, save them as a Postman collection and add simple test scripts for status codes. That collection becomes a quick regression check before every release.
REST API Best Practices and Production Readiness
REST API best practices are mostly about being consistent. Use plural nouns for resources, such as /tasks. Let the HTTP method describe the action, so you never need a route like /getTasks. Return the right status code every time, paginate list routes, and keep one JSON shape for both success and failure. These habits make your API easy to learn and hard to misuse.
How to Secure REST API in Node.js
These checks cover the most common risks I see in Express projects. Apply them before the first real user touches your API.
- Set security headers with helmet, and limit allowed origins with cors.
- Add rate limiting with express-rate-limit, and use a tighter limit on login routes.
- Keep secrets in environment variables, and never commit .env.
- Limit request body size with express.json({ limit }).
- Run npm audit often and keep dependencies updated.
- Serve everything over HTTPS and hash passwords with bcrypt.
Validation also protects you from NoSQL injection. Because the schema demands a string for email, an object such as { "$gt": "" } is rejected before it reaches MongoDB.
How to Deploy Node.js REST API
To deploy a Node.js REST API, set NODE_ENV=production and move every secret into your hosting platform's settings. Use a managed MongoDB cluster with backups and an IP allowlist. Point your load balancer at /health, and run the app with a process manager or container that restarts it after a crash. Also handle SIGTERM, so deploys finish current requests before the process exits.
import mongoose from "mongoose"; const server = app.listen(port, () => console.log(`API running on port ${port}`)); process.on("SIGTERM", () => { server.close(async () => { await mongoose.connection.close(); process.exit(0); });});The table below shows how a few settings change between local work and a live environment.
| Area | Development | Production |
|---|---|---|
| Secrets | .env file on your machine | Platform secret manager |
| Logging | morgan("dev") in the console | Structured logs sent to a central service |
| Database | Local MongoDB | Managed cluster with backups and an IP allowlist |
| Errors | Full details in the terminal | Generic message to clients, full stack in logs |
| CORS | Local front-end URL | Only your real front-end domain |
Early products often ship an API like this first. If you are planning one, MVP development and SaaS development both benefit from a clean structure on day one.
Next Steps for Your Node.js REST API
You now have a working REST API with Node.js and Express that covers the parts real projects need: structure, MongoDB, CRUD routes, validation, error handling, JWT login, and a path to production. The best way to learn from any Node.js REST API tutorial is to extend it. Add task categories, add refresh tokens, write automated tests, then deploy it to a test environment. If you want to see how I apply these ideas in finished builds, browse the projects in my work section.
Frequently Asked Questions About Creating a REST API Using Node.js
Topics
- #Node.js
- #Express
- #REST API
- #Backend Development
- #Express.js Tutorial
- #API Development
- #Postman
- #JavaScript



