1. What is Express

Node.js lets you run JavaScript on a server โ€” but out of the box it gives you very low-level tools. Writing HTTP servers in raw Node requires a lot of boilerplate: parsing URLs, reading request bodies, setting response headers. It gets tedious fast.

Express is a minimal, unopinionated web framework that wraps Node's HTTP module and gives you clean, readable tools for the things you actually need: defining routes, reading request data, and sending responses.

๐Ÿ›’
UrbanCart Example
The backend behind the storefront

UrbanCart's React app runs in the browser โ€” it shows product listings, cart state, and checkout forms. But where does the product data come from? A database. Express sits in the middle: it receives requests from the React frontend (or a mobile app, or curl), talks to the database, and sends back JSON. It is the API layer your frontend calls.

How Express fits in the stack
React Frontend
fetch('/api/products')
โ†’
Express Server
app.get('/api/products')
โ†’
Database
PostgreSQL / MongoDB

Express is one of the most downloaded npm packages of all time. Almost every Node.js backend you encounter โ€” from startups to large-scale production systems โ€” is built on Express or a framework derived from it.

Install Express: Run npm install express in your Node.js project. That's it. No global install needed โ€” Express is a regular npm dependency.

2. Creating a Server

An Express server is created in four lines. You import Express, create an app instance, define at least one route, and start listening on a port.

server.js Basic Express Server
Terminal โ€” starting the server
$ node server.js Server running on http://localhost:3000
๐Ÿญ

app = express()

Creates your Express application. This is the central object โ€” you attach routes, middleware, and configuration to it.

๐Ÿ‘‚

app.listen(3000)

Starts an HTTP server on port 3000. The callback fires once the server is ready to accept connections.

Port 3000: This is the conventional development port for Node/Express. In production, you'll use PORT from environment variables: app.listen(process.env.PORT || 3000). Your React dev server typically runs on port 5173 or 3000 โ€” if there's a conflict, change one.

3. Routes โ€” GET, POST, PUT, DELETE

A route is a combination of an HTTP method and a URL path. Express gives you a method for each HTTP verb. Each method takes a path and a handler function that receives req (request) and res (response).

GET

Read

Fetch a resource. Safe โ€” no side effects.

POST

Create

Create a new resource. Sends data in the body.

PUT

Update

Replace an existing resource entirely.

DELETE

Delete

Remove a resource permanently.

routes/products.js All Four HTTP Methods
REST convention: These four routes map to the four CRUD operations โ€” Create (POST), Read (GET), Update (PUT), Delete (DELETE). This pattern is called a REST API. UrbanCart's backend is built entirely on these four methods.

4. The req and res Objects

Every route handler receives two objects: req (request) contains everything the client sent, and res (response) contains the tools to send something back.

req โ€” Reading the request

server.js Reading from req
๐Ÿ”–

req.params

URL route parameters. /products/:id โ†’ req.params.id. Always a string.

๐Ÿ”

req.query

Query string values. ?sort=price โ†’ req.query.sort. Great for filtering and sorting.

๐Ÿ“ฆ

req.body

JSON body from POST/PUT requests. Requires app.use(express.json()) middleware first.

๐Ÿ“‹

req.headers

HTTP request headers. Commonly used for auth tokens: req.headers.authorization.

res โ€” Sending the response

server.js Sending responses with res
Common HTTP status codes you'll use
200 OK โ€” successful GET / PUT / DELETE 201 Created โ€” successful POST (resource created) 400 Bad Request โ€” client sent invalid data 401 Unauthorized โ€” authentication required 403 Forbidden โ€” authenticated but not allowed 404 Not Found โ€” resource doesn't exist 500 Internal Error โ€” something crashed on the server

5. Route Parameters โ€” /api/products/:id

Route parameters let you capture dynamic values from the URL path. You declare them with a colon (:) in the route definition, and access them via req.params.

server.js GET a single product by ID
Terminal โ€” curl requests and responses
$ curl http://localhost:3000/api/products/1 {"id":1,"name":"Wireless Headphones","price":49.99,"category":"audio"} $ curl http://localhost:3000/api/products/99 {"error":"Product not found"}
Always handle the not-found case. If a client requests /api/products/9999 and that ID doesn't exist, return a 404 with a clear error message. Never let the server return undefined or crash silently.

6. Query Strings โ€” Filtering & Sorting

Query strings appear after the ? in a URL. They are used for optional parameters like filtering, sorting, and pagination. Unlike route parameters, they are not part of the route definition โ€” Express parses them automatically and puts them in req.query.

server.js Filtering products with query strings
Terminal โ€” query string examples
# All products $ curl "http://localhost:3000/api/products" [ {"id":1,"name":"Wireless Headphones","price":49.99,"category":"audio"}, {"id":2,"name":"USB-C Hub","price":29.99,"category":"tech"}, {"id":3,"name":"Laptop Stand","price":39.99,"category":"tech"}, {"id":4,"name":"Mechanical Keyboard","price":89.99,"category":"tech"} ] # Filter by category=audio $ curl "http://localhost:3000/api/products?category=audio" [{"id":1,"name":"Wireless Headphones","price":49.99,"category":"audio"}] # Filter tech + sort by price ascending $ curl "http://localhost:3000/api/products?category=tech&sort=price" [ {"id":2,"name":"USB-C Hub","price":29.99,"category":"tech"}, {"id":3,"name":"Laptop Stand","price":39.99,"category":"tech"}, {"id":4,"name":"Mechanical Keyboard","price":89.99,"category":"tech"} ]
Route params vs query strings: Use route parameters (:id) for identifying a specific resource โ€” /products/42. Use query strings (?category=tech) for optional filters, sorting, and pagination. Never mix these up.

7. Returning JSON โ€” Always Use res.json()

REST APIs communicate in JSON. Express's res.json() serialises any JavaScript object or array, sets the correct Content-Type: application/json header automatically, and sends the response.

server.js POST /api/products โ€” creating a product
Terminal โ€” POST request with curl
# Create a new product $ curl -X POST http://localhost:3000/api/products \ -H "Content-Type: application/json" \ -d '{"name":"Gaming Mouse","price":59.99,"category":"tech"}' { "id": 5, "name": "Gaming Mouse", "price": 59.99, "category": "tech" } # Missing required field โ€” returns 400 $ curl -X POST http://localhost:3000/api/products \ -H "Content-Type: application/json" \ -d '{"name":"Gaming Mouse"}' {"error":"name, price, and category are required"}

8. Complete UrbanCart Products API

Let's put everything together into a complete, working products API. This is the real structure you'll use in production โ€” the same pattern powers Flipkart, Jumia, and Shopify's backends.

server.js Complete UrbanCart Products API
Terminal โ€” testing the complete API
# GET all products $ curl http://localhost:3000/api/products {"count":5,"products":[ {"id":1,"name":"Wireless Headphones","price":49.99,"category":"audio","stock":120}, {"id":2,"name":"USB-C Hub","price":29.99,"category":"tech","stock":85}, {"id":3,"name":"Laptop Stand","price":39.99,"category":"tech","stock":60}, {"id":4,"name":"Mechanical Keyboard","price":89.99,"category":"tech","stock":40}, {"id":5,"name":"Ring Light","price":34.99,"category":"studio","stock":200} ]} # GET a single product $ curl http://localhost:3000/api/products/3 {"id":3,"name":"Laptop Stand","price":39.99,"category":"tech","stock":60} # PUT โ€” update product price $ curl -X PUT http://localhost:3000/api/products/3 \ -H "Content-Type: application/json" \ -d '{"price":44.99}' {"id":3,"name":"Laptop Stand","price":44.99,"category":"tech","stock":60} # DELETE a product $ curl -X DELETE http://localhost:3000/api/products/5 {"message":"Product deleted","product":{"id":5,"name":"Ring Light",...}}
This is a real REST API. Replace the in-memory products array with database queries and you have production-ready code. The route structure, status codes, and response shapes are exactly what Flipkart, Jumia, and Shopify use.

Quiz

Question 1 of 5
What does app.listen(3000) do?
Question 2 of 5
How do you access a URL parameter like /products/:id inside an Express route handler?
Question 3 of 5
Which method sends a JSON response in Express and automatically sets the correct Content-Type header?
Question 4 of 5
How do you access query string parameters like ?sort=price in an Express route handler?
Question 5 of 5
What HTTP method should you use to create a new resource in a REST API?
0
/ 5
Great job!

You completed the Express Basics quiz.

Next Lesson

Middleware & Error Handling โ†’
You've got Express routing mastered. Next: middleware pipelines, error handlers, and CORS.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just built a REST API from scratch.
Now build a backend career that scales.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’