Skip to main content
Node.js Basics
CHAPTER 13 Beginner

Express.js Introduction

Updated: May 13, 2026
20 min read

# Express.js Introduction

Welcome to Chapter 13! You survived the raw Node.js modules. You've seen how tedious it is to build a server using http.createServer, manually parse URLs with if/else statements, and manually set HTTP headers.

In the real world, virtually nobody does that. We use Express.js. Express is a fast, unopinionated, minimalist web framework built *on top* of the Node.js http module. It does all the heavy lifting for you.

---

1. Introduction

If Node.js is the engine of a car, Express.js is the steering wheel, the pedals, and the dashboard. It makes driving the car infinitely easier.

Express is an NPM package. It abstracts away the complex, repetitive code required to set up a server and handle routing. It is the "E" in the famous MERN stack (MongoDB, Express, React, Node) and MEAN stack.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Install Express.js using NPM.
  • Instantiate an Express application.
  • Create a basic server that listens on a port.
  • Define simple GET routes using Express syntax.
  • Understand how Express simplifies the req and res objects.

---

3. Beginner-Friendly Explanations

What does "Framework" mean?

A library (like date-fns) is a tool you call when you need it. A framework dictates how you structure your entire app. Express provides a structured way to handle incoming requests, route them to the correct code, and send responses easily.

The Express Way vs The Raw Way

Raw Node:
javascript
1234
if (req.url === '/about' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(&#039;<h1>About</h1>&#039;);
}

Express.js:

javascript
123
app.get(&#039;/about&#039;, (req, res) => {
    res.send(&#039;<h1>About</h1>&#039;); // Automatically sets headers & ends response!
});

Look how clean that is! res.send() is a magical Express method that automatically figures out you are sending HTML, sets the status to 200, sets the Content-Type, and ends the response for you.

---

4. Syntax Explanation

Let's look at the absolute minimum code required to start an Express server.

```javascript id="ch13-syntax-1" // 1. Require the express package const express = require('express');

// 2. Create the express application instance (traditionally named 'app') const app = express();

// 3. Define a route (When a user visits the root '/') app.get('/', (req, res) => { res.send('Hello from Express!'); });

// 4. Start the server app.listen(3000, () => { console.log('Express server is running on port 3000'); });

12345678910111213141516171819202122
**Output Explanation:**
When you run this file, Express spins up an HTTP server under the hood. If a user visits `localhost:3000`, the `app.get('/')` route intercepts the request and fires the callback function, sending the text back to the browser.

---

## 5. Real-world Examples

**Why is Express so popular?**
Every time you open Twitter, your browser sends hundreds of background requests:
- `GET /api/tweets` (to fetch the feed)
- `POST /api/like` (when you click the heart icon)
- `GET /api/messages` (to check your DMs)

Express makes handling these different paths and methods incredibly clean and organized. Netflix, Uber, and IBM all use Express.js for massive portions of their backend architecture.

---

## 6. Multiple Code Examples

### Example 1: Installing Express
You must install Express in your project folder before you can use it.

bash id="ch13-bash-1" npm init -y npm install express

123
### Example 2: Sending JSON Data
In modern web development, servers often don't send HTML. Instead, they send JSON data (an API), and the frontend (like React or Vue) uses that data to build the HTML. Express has a built-in `.json()` method for this!

javascript id="ch13-code-1" const express = require('express'); const app = express();

app.get('/api/user', (req, res) => { const user = { name: "Alice", role: "Admin", age: 25 }; // Express automatically converts the object to a JSON string // and sets Content-Type to application/json res.json(user); });

app.listen(3000);

123
### Example 3: Handling 404 Pages
In raw Node, we had a `default` switch case. In Express, you put a generic `app.use()` at the very bottom of your file. If a request doesn't match any routes above it, it falls down into this function.

javascript id="ch13-code-2" const express = require('express'); const app = express();

app.get('/', (req, res) => res.send('Home Page')); app.get('/about', (req, res) => res.send('About Page'));

// 404 Handler (MUST be placed after all other routes) app.use((req, res) => { // Chain status() and send() together res.status(404).send('<h1>404 - Sorry, page not found!</h1>'); });

app.listen(3000);

1234567891011121314151617181920212223242526272829303132333435363738
---

## 7. Output Explanations

What is `res.status()`?
By default, `res.send()` assumes everything is OK and sends a `200` status code. If an error occurs, you can use `res.status(404).send(...)` to manually change the HTTP status code before the response is sent.

---

## 8. Common Mistakes

1. **Forgetting to install express:** You cannot just require Express. You must run `npm install express` first!
2. **Order of Routes:** Express reads files from top to bottom. If you place the 404 `app.use()` at the *top* of the file, it will intercept every single request, and your actual routes will never trigger!
3. **Using `res.end` instead of `res.send`:** While `res.end` still works (because Express is built on `http`), you should always use `res.send` or `res.json` in Express to take advantage of its automatic header formatting.

---

## 9. Best Practices

- **Organize your routes:** Keep your routes logical. API routes should start with `/api/` (e.g., `/api/users`).
- **Use Nodemon:** Since you are now building real servers, always run your app using `nodemon` so you don't have to constantly restart the server when you add new routes.
- **Keep callbacks clean:** If your route logic is very long (e.g., 50 lines of database queries), don't write it directly inside `app.get`. Move it to a separate function!

---

## 10. Exercises

1. Initialize a project, install express, and create a `server.js` file.
2. Create an Express server with three routes: `/` (returns "Welcome"), `/cats` (returns "Meow"), and `/dogs` (returns "Woof").
3. Add a 404 catch-all route at the bottom that returns "Animal not found".

---

## 11. Mini Project: Express starter app

**Objective:** Build a robust Express starter template that we can use for future chapters.

**Step 1:** Terminal Setup

bash mkdir express-starter cd express-starter npm init -y npm install express npm install -D nodemon

1
**Step 2:** Edit `package.json` scripts

json "scripts": { "start": "node app.js", "dev": "nodemon app.js" }

1
**Step 3:** Code (`app.js`)

javascript id="ch13-mini-project" // app.js const express = require('express'); const app = express(); const PORT = 3000;

// Home Route app.get('/', (req, res) => { res.send( <h1>Welcome to Express!</h1> <p>Try visiting <a href="/api/info">/api/info</a></p> ); });

// API Route returning JSON app.get('/api/info', (req, res) => { res.json({ framework: "Express.js", version: "4.x", status: "Active" }); });

// 404 Route app.use((req, res) => { res.status(404).json({ error: "Route not found" }); });

// Start Server app.listen(PORT, () => { console.log(🚀 Express Server running on http://localhost:${PORT}); }); ``

Run it: npm run dev

---

12. Coding Challenges

Challenge 1: Create a route /random that generates a random number between 1 and 100 and sends it back to the client as an HTML <h1> tag.

Challenge 2: Look up the res.redirect() method in the Express documentation. Create a route /google that automatically redirects the user to https://www.google.com.

---

13. MCQs with Answers

Q1: What is Express.js? A) A database management system. B) A new programming language. C) A fast, minimalist web framework for Node.js. D) A built-in core Node module. Answer: C

Q2: Which method is used to send a JavaScript object back to the client as JSON? A) res.sendObject() B) res.json() C) res.end() D) res.write() Answer: B

Q3: Why is res.send() better than the raw res.end()? A) It executes faster. B) It automatically sets the Content-Type header and status codes. C) It compresses the data. D) It prevents server crashes. Answer: B

Q4: Where should the 404 Not Found handler be placed in an Express file? A) At the very top. B) Inside the app.listen callback. C) At the very bottom, after all other routes. D) It doesn't matter. Answer: C

---

14. Interview Questions

  1. 1. Why use Express instead of the built-in HTTP module?
*Answer:* The raw HTTP module requires a lot of boilerplate code to handle routing, parse request bodies, and format responses. Express abstracts this complexity, providing clean routing methods (
app.get, app.post) and helpful response methods (res.json, res.sendFile), vastly speeding up development.
  1. 2. What does res.json() do under the hood?
*Answer:* It converts the provided JavaScript object or array into a JSON string using JSON.stringify(), sets the Content-Type header to application/json, and then calls res.send() to transmit the data.

---

15. FAQs

Q: Do I have to use Express? A: No, there are other frameworks like Fastify, Koa, and NestJS. However, Express is the industry standard and has the largest community, making it the perfect framework to learn first.

Q: Is Express frontend or backend? A: Strictly Backend. It runs on the server and listens for requests coming from the frontend.

---

16. Summary

  • Express.js is a third-party NPM package that simplifies building web servers.
  • Instantiate an app using const app = express().
  • Define routes simply using methods like app.get('/path', callback).
  • Use res.send() for HTML/text, and res.json() for APIs.
  • Express evaluates routes from top to bottom, making a bottom app.use perfect for 404 errors.

---

17. Next Chapter Recommendation

We've only touched GET` requests so far. What happens when a user submits a form or tries to log in? In Chapter 14: Express.js Routing, we will dive deeper into advanced routing, POST requests, and dynamic route parameters!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·