TeknoTUT

Build a REST API with Node.js and Express 5 for Beginners

Learn how to build a REST API with Node.js and Express 5 from scratch: routing, CRUD, validation, error handling, and testing with curl.

Written by 13 min readBahasa Indonesia
Illustration of an API server exchanging JSON data with a laptop and a phone
On This Page

If you are a web developer, you're probably familiar with the term API. A mobile app listing products, a dashboard loading charts, an IoT device sending sensor readings: almost all of them talk to a server through an API.

The problem is that building your own API can feel intimidating when you're just starting out. Where do you begin? How do you receive JSON data? Which status code should you send back? On top of that, many tutorials online still use old patterns that no longer match the latest version.

This is where Express comes in. Express is the most popular web framework for Node.js, and since Express 5 became the default version on npm, a few important changes make our code shorter, especially when it comes to error handling.

In this article, we'll walk through building a REST API with Node.js and Express 5, from setting up the project, creating CRUD endpoints, and validating input, to handling errors and testing everything with curl. Let's get started!

What is a REST API?

An API (Application Programming Interface) is the "door" an application provides so that other applications can request or send data. REST (Representational State Transfer) is an API design style that uses HTTP as it is: URLs represent data (called resources), and HTTP methods represent actions on that data.

Think of a restaurant. You (the client) don't walk into the kitchen (the database). You order through a waiter (the API) in an agreed way, and the waiter brings back the result, usually as JSON.

In a REST API, each HTTP method has a clear role:

Method Example Endpoint Purpose Success Status Code
GET /todos Fetch all items 200 OK
GET /todos/1 Fetch one item 200 OK
POST /todos Create a new item 201 Created
PATCH /todos/1 Update part of an item 200 OK
DELETE /todos/1 Delete an item 204 No Content

Those five endpoints are exactly what we'll build in this article, as a simple todo list API.

Why Use Express 5?

Node.js can run an HTTP server without any framework. However, you would have to parse URLs, read request bodies, and handle routing by hand. Express takes care of all that with a very simple API.

A few reasons to pick Express 5:

  • Lightweight and minimal: Express only gives you routing and middleware. The rest is up to you, which makes it great for learning because there's no hidden magic.
  • Huge ecosystem: almost every need (authentication, file uploads, CORS, rate limiting) already has a middleware.
  • Errors in async functions are handled automatically: in Express 5, a rejected promise inside a handler is forwarded to the error-handling middleware. In Express 4, you had to wrap it in try...catch yourself.
  • It's the default version: npm install express now installs Express 5. At the time of writing, the latest version is 5.3.

Drawbacks You Should Know

To keep things balanced, here are a couple of things to be aware of:

  • No enforced structure: Express doesn't dictate your folder layout or how you validate data. On large projects you need your own discipline (or a more complete framework such as NestJS).
  • Lots of outdated tutorials: most tutorials online were written for Express 4. Some syntax, like the /* wildcard route, no longer works in Express 5. We'll cover the differences near the end.

Preparation

Before we begin, make sure you have:

  • Node.js 18 or newer, since that's the minimum Express 5 requires. An LTS version is strongly recommended, meaning Node.js 24 or Node.js 26. The node --watch command used in this article needs Node.js 22 or later. If Node.js isn't installed yet, follow the how to install Node.js article.
  • A terminal and a text editor such as VS Code.
  • curl to test the API. It ships with macOS, most Linux distros, and Windows 10/11.

Check your Node.js and npm versions with the following commands:

node --version
npm --version

If the output shows version numbers (for example v24.x.x), you're ready to continue. The code in this article is written for Express 5 on Node.js 22 or later.

How to Build a REST API with Express 5

Step #1: Create a New Project

Create a project folder and move into it:

mkdir todo-api
cd todo-api

Initialize a Node.js project with the following command. The -y flag creates a package.json file with default values, skipping the questions.

npm init -y

In this article we use ES Modules syntax (import), the modern JavaScript module standard. Enable it by setting type to module in package.json:

npm pkg set type=module

Finally, install Express:

npm install express

To confirm that Express 5 is what got installed, run this command:

npm list express

The output looks roughly like this:

[email protected] /home/budi/todo-api
└── [email protected]

If the leading number is 5, you're on Express 5.

Step #2: Create Your First Server

Create a file named app.js inside the project folder and add the following code:

import express from "express";
 
const app = express();
const PORT = process.env.PORT || 3000;
 
app.get("/", (req, res) => {
  res.json({ message: "Todo API is running" });
});
 
app.listen(PORT, (error) => {
  if (error) throw error;
  console.log(`Server running at http://localhost:${PORT}`);
});

A quick explanation of the code above:

  • express() creates an Express application.
  • app.get("/", ...) registers a route: when a GET request hits /, run the function that follows. This function is called a handler and receives req (the request) and res (the response).
  • res.json() sends a JSON response with the correct Content-Type header.
  • app.listen() starts the server on the given port. In Express 5, its callback also receives an error, for example when the port is already used by another application.

Start the server with this command:

node --watch app.js

The --watch flag makes Node.js restart the server automatically whenever a file changes, so you no longer need to install nodemon. Keep this terminal open.

Open a new terminal and test it with curl:

curl http://localhost:3000/

If you see the output below, congratulations, your first server is up and running!

{"message":"Todo API is running"}

Step #3: Set Up the Data and the JSON Middleware

To keep the focus on Express, we'll store data in an in-memory array. Add the following code to app.js, right below the const PORT line:

app.use(express.json());
 
let nextId = 3;
const todos = [
  { id: 1, title: "Learn Express", done: true },
  { id: 2, title: "Build a REST API", done: false },
];

The app.use(express.json()) line installs Express's built-in middleware that reads JSON request bodies and stores the result in req.body. Middleware is a function that runs before a request reaches its handler, much like a checkpoint every request has to pass.

Note: because the data lives in memory only, every change is lost when the server restarts. That's fine for learning. In a real application, replace this array with a database such as SQLite, PostgreSQL, or MongoDB.

Step #4: Create Endpoints to Read Data (GET)

Now let's create two endpoints: one to fetch all todos, and one to fetch a single todo by its id. Add the following code above the app.listen line:

app.get("/todos", (req, res) => {
  const { done } = req.query;
  if (done === undefined) return res.json(todos);
  res.json(todos.filter((todo) => String(todo.done) === done));
});
 
app.get("/todos/:id", (req, res) => {
  const todo = todos.find((item) => item.id === Number(req.params.id));
  if (!todo) return res.status(404).json({ error: "Todo not found" });
  res.json(todo);
});

There are two new things here:

  • req.query holds the URL's query string. That way, /todos?done=true returns only the completed todos.
  • :id is a route parameter. Its value is available in req.params.id as a string, so we convert it to a number with Number().

If the todo isn't found, we return a 404 status code along with an error message. Returning the right status code is one of the marks of a good REST API.

Test both endpoints:

curl http://localhost:3000/todos
curl http://localhost:3000/todos/2
curl "http://localhost:3000/todos?done=true"

The output of the first command looks roughly like this:

[{"id":1,"title":"Learn Express","done":true},{"id":2,"title":"Build a REST API","done":false}]

Step #5: Create an Endpoint to Add Data (POST)

The next endpoint accepts JSON data from the client. Add the following code below the GET endpoints:

app.post("/todos", (req, res) => {
  const title = req.body?.title;
  if (typeof title !== "string" || title.trim() === "") {
    return res.status(400).json({ error: "Field 'title' is required" });
  }
 
  const todo = { id: nextId++, title: title.trim(), done: false };
  todos.push(todo);
  res.status(201).json(todo);
});

Never blindly trust data sent by a client. Here we do some simple validation: title must be a string and can't be empty. If it's invalid, we return 400 Bad Request. If it's valid, we return 201 Created along with the newly created item.

Why req.body?.title instead of req.body.title? In Express 5, req.body is undefined when the body hasn't been parsed, for example when the client forgets the Content-Type: application/json header. In Express 4, it was {}. Without the ?., our code would throw and the client would get a 500, even though the request is what's wrong.

Test it by sending JSON data. The -i flag prints the response headers so you can see the status code:

curl -i -X POST http://localhost:3000/todos -H "Content-Type: application/json" -d '{"title":"Deploy to VPS"}'

The important part of the output looks roughly like this:

HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
 
{"id":3,"title":"Deploy to VPS","done":false}

Windows users: the single quotes in the command above aren't understood by Command Prompt. Run curl from Git Bash or WSL, or use an app like Postman.

Also try sending an empty body with -d '{}'. You should get 400 Bad Request with the message Field 'title' is required.

Step #6: Create Endpoints to Update and Delete Data (PATCH & DELETE)

To update data we use PATCH, because the client may send only some of the fields (for example just done). Add the following code:

app.patch("/todos/:id", (req, res) => {
  const todo = todos.find((item) => item.id === Number(req.params.id));
  if (!todo) return res.status(404).json({ error: "Todo not found" });
 
  const { title, done } = req.body ?? {};
  if (title !== undefined) {
    if (typeof title !== "string" || title.trim() === "") {
      return res.status(400).json({ error: "Field 'title' must be a non-empty string" });
    }
    todo.title = title.trim();
  }
  if (done !== undefined) {
    if (typeof done !== "boolean") {
      return res.status(400).json({ error: "Field 'done' must be a boolean" });
    }
    todo.done = done;
  }
 
  res.json(todo);
});
 
app.delete("/todos/:id", (req, res) => {
  const index = todos.findIndex((item) => item.id === Number(req.params.id));
  if (index === -1) return res.status(404).json({ error: "Todo not found" });
 
  todos.splice(index, 1);
  res.status(204).end();
});

In the DELETE endpoint we return 204 No Content: it succeeded, but there's nothing to send back. That's why we use .end() instead of .json().

Mark todo number 2 as done, then delete todo number 1:

curl -X PATCH http://localhost:3000/todos/2 -H "Content-Type: application/json" -d '{"done":true}'
curl -i -X DELETE http://localhost:3000/todos/1

The first command returns the todo with "done":true, and the second one shows HTTP/1.1 204 No Content.

Step #7: Handle Unknown Routes and Errors

Try requesting an address that doesn't exist, for example curl http://localhost:3000/users. Express replies with an HTML page, while our API clients expect JSON. The same thing happens when a client sends broken JSON.

To fix this, add the two middleware functions below after all routes and before app.listen. The order matters, because Express runs middleware from top to bottom.

app.use((req, res) => {
  res.status(404).json({ error: `Route ${req.method} ${req.originalUrl} not found` });
});
 
app.use((err, req, res, next) => {
  if (err.type === "entity.parse.failed") {
    return res.status(400).json({ error: "Invalid JSON body" });
  }
  console.error(err);
  res.status(500).json({ error: "Internal server error" });
});

The first middleware catches every request that didn't match any route. The second one is the error-handling middleware. Express recognizes it by its parameter count, which must be four (err, req, res, next), so don't remove next even though it isn't used.

Inside it, we check err.type. The value entity.parse.failed is how express.json() signals that the body isn't valid JSON, so we answer with a 400. Any other error is logged on the server, and the client only gets a generic message.

Important: never send err.message or err.stack to the client in production. Error details can leak information about your code structure and your server.

Test it by sending broken JSON:

curl -X POST http://localhost:3000/todos -H "Content-Type: application/json" -d '{"title":'

If the output is {"error":"Invalid JSON body"}, your error handling works.

Handling Errors in Async Handlers in Express 5

Once you bring in a database, nearly every handler becomes an async function. This is where one of the biggest benefits of Express 5 shows.

Look at the following example, where db.findTodos() stands in for a database function that can fail:

app.get("/todos", async (req, res) => {
  const rows = await db.findTodos();
  res.json(rows);
});

In Express 4, if db.findTodos() failed, the error went uncaught and the request would hang, unless you wrapped it in try...catch and called next(err). In Express 5, the rejected promise is automatically forwarded to the error-handling middleware we wrote in Step #7. The code ends up much cleaner.

Express 5 vs Express 4 Differences That Often Trip People Up

If you're following an older tutorial or moving a project from Express 4, watch out for these changes:

Topic Express 4 Express 5
Minimum Node.js version 0.10 18
Errors in async handlers Needs try...catch + next(err) Forwarded automatically
req.body without a parser {} undefined
Wildcard routes /* /*splat (a name is required)
Optional parameters /:file.:ext? /:file{.:ext}
req.query Writable Read-only (a getter)
res.send(status), res.json(obj, status) Still available Removed, use res.status(...).json(...)
app.del() Still available Removed, use app.delete()

You can read the full list in the Express 5 migration guide.

Tips for a Cleaner and Safer REST API

Tip #1: Split Routes with express.Router

As the number of endpoints grows, app.js gets bloated quickly. Move related routes into their own file with express.Router(). Here's an example routes/todos.js file:

import { Router } from "express";
 
const router = Router();
 
router.get("/", (req, res) => {
  res.json([]);
});
 
export default router;

Then mount it in app.js under the /todos prefix:

import todosRouter from "./routes/todos.js";
 
app.use("/todos", todosRouter);

This way, paths inside the router are simply / and /:id, because the /todos prefix is set when the router is mounted.

Tip #2: Hide the X-Powered-By Header

By default, Express sends an X-Powered-By: Express header with every response. That makes it easier for attackers to identify the framework you use. Turn it off with this single line after const app = express():

app.disable("x-powered-by");

Tip #3: Keep Configuration in Environment Variables

We already wrote process.env.PORT || 3000, so the port can change without touching the code. Try running the server on another port with this command:

PORT=4000 node app.js

For more configuration (a database address, for example), put it in a .env file and run node --env-file=.env app.js. This feature is built into Node.js, so the dotenv package is no longer needed. Don't forget to add .env to .gitignore.

Conclusion

From this article, we can conclude that building a REST API with Node.js and Express 5 isn't hard at all. With a single file and fewer than a hundred lines of code, we have a complete CRUD API with input validation, proper HTTP status codes, and JSON responses for unknown routes and errors.

Things to Remember

  • Install express.json() so JSON bodies get parsed, and remember that req.body can be undefined in Express 5.
  • Always validate input, then return the matching status code: 200, 201, 204, 400, 404, and 500.
  • Put the 404 middleware and the error-handling middleware last.
  • In Express 5, errors in async handlers reach the error-handling middleware automatically.

Next Steps

The API we built still keeps its data in memory. Good next steps are connecting it to a database, adding authentication, and running it on a server.

To run a Node.js application on a VPS, you can follow the same pattern as in the deploy Next.js to a VPS with PM2 and Nginx article, or turn it into a service with a systemd service.


I hope this article helps.

Continue Reading

More articles you might enjoy.