If you are learning backend development with JavaScript, you will eventually come across Node.js and Express.js.
Node.js allows us to run JavaScript outside the browser.
But when we start building real backend applications, we need features such as:
-
Creating API endpoints
-
Handling HTTP requests
-
Sending responses
-
Working with routes
-
Handling middleware
-
Managing errors
-
Connecting to databases
-
Building REST APIs
This is where Express.js becomes useful.
In this beginner-friendly guide, we'll understand what Express.js is and then build our first API from scratch.
By the end of this article, you'll have a small Express.js server running locally and responding to HTTP requests.
What Is Express.js?
Express.js is a lightweight and flexible web framework for Node.js.
It makes it easier to build:
-
Web servers
-
REST APIs
-
Backend applications
-
Web applications
-
Microservices
Without Express.js, we can create a server using Node.js's built-in http module.
For example:
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello World");
});
server.listen(3000);
This works.
But as our application grows, handling routes, requests, responses, middleware, and errors manually can become difficult.
Express.js provides a simpler way to handle these things.
With Express, the same idea becomes:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
Much cleaner.
That's one of the main reasons Express.js became so popular in the Node.js ecosystem.
Node.js vs Express.js
Before going further, let's clear up one common confusion.
Node.js and Express.js are not the same thing.
Node.js
Node.js is a JavaScript runtime.
It allows us to execute JavaScript on the server.
For example:
Browser
↓
JavaScript
Node.js
↓
JavaScript outside the browser
Express.js
Express.js is a framework that runs on Node.js.
It provides tools that make server and API development easier.
Think of it like this:
Node.js
↓
Runtime
Express.js
↓
Web framework running on Node.js
A simple analogy:
Node.js gives us the engine. Express.js gives us a convenient framework for building the application around that engine.
Why Do We Need Express.js?
Node.js already provides functionality for creating servers.
So why do we need Express?
Imagine building an application with multiple APIs:
GET /users
GET /users/:id
POST /users
PUT /users/:id
DELETE /users/:id
GET /products
GET /products/:id
POST /products
If we handle everything directly using Node's http module, the code can become difficult to maintain.
Express provides a clean API for defining routes:
app.get("/users", ...);
app.get("/users/:id", ...);
app.post("/users", ...);
app.put("/users/:id", ...);
app.delete("/users/:id", ...);
This makes our backend code easier to understand and maintain.
What Can We Build with Express.js?
Express.js can be used to build many different types of applications.
For example:
REST APIs
GET /api/users
POST /api/users
GET /api/products
Authentication APIs
POST /api/auth/register
POST /api/auth/login
POST /api/auth/logout
E-commerce backends
/api/products
/api/orders
/api/cart
/api/payments
Blog backends
/api/blogs
/api/comments
/api/users
Admin dashboards
/api/admin/users
/api/admin/reports
/api/admin/settings
And many more.
What Are We Going to Build?
Instead of jumping directly into a complicated application, let's start with something simple.
We're going to create this API:
GET /api/hello
When we call it, the server will return:
{
"message": "Hello from Express.js!"
}
Our final flow will look like:
Client
|
| GET /api/hello
↓
Express Server
|
| JSON response
↓
Client
Let's build it step by step.
Step 1: Install Node.js
Before using Express.js, we need Node.js installed on our computer.
You can verify whether Node.js is already installed by opening your terminal and running:
node --version
You should see something similar to:
v22.x.x
You can also check npm:
npm --version
If both commands return versions, you're ready to continue.
Step 2: Create a Project
Create a new directory for our Express application.
mkdir express-first-api
Move into the directory:
cd express-first-api
Now initialize a Node.js project:
npm init -y
This creates:
package.json
Your project currently looks like:
express-first-api/
└── package.json
Step 3: Install Express.js
Now install Express:
npm install express
npm downloads Express and adds it to your project's dependencies.
Your package.json will now contain something similar to:
{
"name": "express-first-api",
"version": "1.0.0",
"dependencies": {
"express": "^5.x.x"
}
}
The exact version may be different depending on when you install it.
Step 4: Create the Server File
Create a file called:
server.js
Our project now looks like:
express-first-api/
│
├── node_modules/
├── package.json
├── package-lock.json
└── server.js
Open server.js.
Add:
const express = require("express");
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Let's understand this code.
Understanding the Express Code
Import Express
const express = require("express");
This imports the Express package.
We're storing it in a variable called:
express
Create the Express Application
const app = express();
This creates our Express application.
The app object provides methods such as:
app.get()
app.post()
app.put()
app.patch()
app.delete()
app.use()
app.listen()
We'll learn these throughout our Express.js journey.
Define the Port
const PORT = 3000;
Our server will run on port 3000.
So we'll access it through:
http://localhost:3000
Start the Server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
app.listen() starts the HTTP server.
When the server starts successfully, the callback function runs:
() => {
console.log(`Server running on http://localhost:${PORT}`);
}
You should see:
Server running on http://localhost:3000
Step 5: Start the Server
Run:
node server.js
You should see:
Server running on http://localhost:3000
Your Express server is now running.
But we haven't created an API yet.
Let's do that.
Step 6: Create Your First API
Add this code before app.listen():
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from Express.js!"
});
});
Your complete server.js now looks like:
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from Express.js!"
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
That's it.
You've just created your first Express.js API.
Step 7: Test the API
Start the server:
node server.js
Open your browser and visit:
http://localhost:3000/api/hello
You should receive:
{
"message": "Hello from Express.js!"
}
Congratulations!
You have created your first Express.js API.
Understanding app.get()
Let's look at this code again:
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from Express.js!"
});
});
There are three important parts.
app.get()
↓
Route
↓
Handler
Let's break it down.
app
app
This is our Express application.
get()
app.get()
This tells Express that we're handling an HTTP GET request.
HTTP methods include:
GET
POST
PUT
PATCH
DELETE
We'll explore these in detail in future articles.
Route
"/api/hello"
This is the URL path.
So our API URL becomes:
http://localhost:3000/api/hello
Request and Response
(req, res) => {
}
These are commonly called:
req → Request
res → Response
The request contains information coming from the client.
The response is what our server sends back.
What Is req?
req represents the incoming HTTP request.
For example, it can contain:
-
Request parameters
-
Query parameters
-
Request body
-
Headers
-
HTTP method
-
URL information
For example:
app.get("/api/hello", (req, res) => {
console.log(req.method);
console.log(req.url);
res.json({
message: "Hello from Express.js!"
});
});
If we request:
GET /api/hello
we could see:
GET
/api/hello
What Is res?
res represents the response that our server sends back to the client.
Express provides several useful response methods.
For example:
res.send()
res.json()
res.status()
We'll focus on res.json() for our API.
Sending JSON Response
We can send JSON using:
res.json({
message: "Hello from Express.js!"
});
The client receives:
{
"message": "Hello from Express.js!"
}
This is commonly used when building REST APIs.
res.send() vs res.json()
You can also write:
res.send("Hello from Express.js!");
This sends a text response.
Whereas:
res.json({
message: "Hello from Express.js!"
});
sends JSON.
For APIs, res.json() is generally more descriptive when you're intentionally returning JSON data.
Let's Create Another API
Now let's create:
GET /api/users
Add:
app.get("/api/users", (req, res) => {
res.json([
{
id: 1,
name: "John"
},
{
id: 2,
name: "Jane"
}
]);
});
Our server now has two APIs:
GET /api/hello
GET /api/users
Visit:
http://localhost:3000/api/users
You'll get:
[
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Jane"
}
]
Our Complete Server
At this point, our server.js looks like:
const express = require("express");
const app = express();
const PORT = 3000;
// Hello API
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from Express.js!"
});
});
// Users API
app.get("/api/users", (req, res) => {
res.json([
{
id: 1,
name: "John"
},
{
id: 2,
name: "Jane"
}
]);
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
This is already a small Express API server.
But there's one problem.
Every time we modify the code, we need to stop and restart the server manually.
Let's improve that.
Step 8: Use Nodemon for Development
nodemon automatically restarts the server whenever files change.
Install it as a development dependency:
npm install --save-dev nodemon
Then update package.json:
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
}
Now run:
npm run dev
You'll see something like:
[nodemon] starting `node server.js`
Server running on http://localhost:3000
Now modify your server code.
Nodemon automatically restarts the application.
This is very useful during development.
Step 9: Add a Root Route
Currently, if you open:
http://localhost:3000
you'll get an error such as:
Cannot GET /
That's because we haven't defined a route for /.
Let's add one:
app.get("/", (req, res) => {
res.send("Welcome to my Express API");
});
Now:
GET /
returns:
Welcome to my Express API
Understanding the Request Flow
Let's understand what happens when we call:
GET /api/hello
The process is:
Browser / Frontend
|
| HTTP GET request
↓
Express Server
|
| Find matching route
↓
app.get("/api/hello")
|
| Execute handler
↓
res.json(...)
|
| JSON response
↓
Browser / Frontend
This is the basic idea behind an API.
Testing APIs with Postman
You don't have to use a browser to test APIs.
Tools such as Postman can be used to send HTTP requests.
For our API:
Method:
GET
URL:
http://localhost:3000/api/hello
Click Send.
You should receive:
{
"message": "Hello from Express.js!"
}
Postman becomes particularly useful when testing:
POST
PUT
PATCH
DELETE
requests because those requests usually contain request bodies.
Testing with curl
You can also test the API directly from your terminal:
curl http://localhost:3000/api/hello
The response should be:
{
"message": "Hello from Express.js!"
}
This is useful when working with APIs from the command line.
What Happens If the Route Doesn't Exist?
Try visiting:
http://localhost:3000/api/products
We haven't created that route.
Express will return:
Cannot GET /api/products
This is because Express couldn't find a matching route for:
GET /api/products
Later, we can create custom error-handling middleware to return a cleaner response.
For example:
{
"message": "Route not found"
}
Why API Routes Usually Start with /api
You'll often see APIs written like:
/api/users
/api/products
/api/orders
/api/blogs
The /api prefix isn't required by Express.
You could create:
/users
/products
/orders
But using /api makes it clear that the route belongs to your API.
For example:
Website:
https://example.com
API:
https://example.com/api/users
This is a common convention.
A Better Project Structure
For this first example, putting everything in server.js is perfectly fine.
But real applications quickly become much larger.
Instead of:
server.js
containing hundreds or thousands of lines, we can eventually organize the application like this:
src/
│
├── controllers/
├── routes/
├── services/
├── middleware/
├── models/
├── config/
└── app.js
server.js
For example:
routes
↓
controllers
↓
services
↓
database
We'll explore this architecture as we move toward production-ready Express applications.
What We Have Learned
In this tutorial, we started with almost nothing and built a working Express.js API.
We learned:
-
What Node.js is
-
What Express.js is
-
Why Express.js is useful
-
How to create a Node.js project
-
How to install Express
-
How to create an Express application
-
How to start an Express server
-
How to create a
GETAPI -
How to use
reqandres -
How to return JSON
-
How to create multiple routes
-
How to use Nodemon
-
How to test an API
Our final API looks like this:
GET /
GET /api/hello
GET /api/users
Complete Final Code
Here's the complete beginner-friendly version:
const express = require("express");
const app = express();
const PORT = 3000;
// Root route
app.get("/", (req, res) => {
res.send("Welcome to my Express API");
});
// Hello API
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from Express.js!"
});
});
// Users API
app.get("/api/users", (req, res) => {
res.json([
{
id: 1,
name: "John"
},
{
id: 2,
name: "Jane"
}
]);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Start it with:
npm run dev
Then test:
http://localhost:3000
http://localhost:3000/api/hello
http://localhost:3000/api/users
What's Next?
Creating a GET API is only the beginning.
A real Express.js application needs to handle different types of requests.
A natural learning path is:
Express.js Basics
↓
Routing
↓
Request & Response
↓
Middleware
↓
POST APIs
↓
Request Body
↓
PUT / PATCH APIs
↓
DELETE APIs
↓
Route Parameters
↓
Query Parameters
↓
Error Handling
↓
Custom Middleware
↓
Controllers & Services
↓
MongoDB + Mongoose
↓
Authentication & JWT
↓
Validation
↓
Security
↓
Testing
↓
Production Deployment
The important thing is not to rush through all of these topics.
First, make sure you understand the basic request-response cycle:
Client
↓
HTTP Request
↓
Express Route
↓
Route Handler
↓
Business Logic
↓
HTTP Response
↓
Client
Once this flow becomes clear, learning the rest of Express.js becomes much easier.
Final Thoughts
Express.js doesn't try to hide what is happening in the backend. Instead, it gives us a simple way to work with Node.js and HTTP.
Our first API was only a few lines of code:
app.get("/api/hello", (req, res) => {
res.json({
message: "Hello from Express.js!"
});
});
But behind those few lines is a fundamental backend concept:
A client sends a request, the server processes it, and the server sends a response back.
That's the foundation of almost every API you'll build.
From here, you can start learning how Express handles POST requests, middleware, route parameters, databases, authentication, validation, error handling, and eventually production-ready backend architecture.