Express.js Deep Dive - Complete Technical Guide
Express.js is a fast, unopinionated, minimalistic web framework for Node.js, designed for building web applications and APIs.1. Express.js Fundamentals
Why Express.js Over Node.js?
| Aspect | Node.js | Express.js |
|---|---|---|
| Code Length | Lengthy, verbose | Concise, minimal |
| Built-in Functions | Limited | Many helper functions |
| Routing | Manual implementation | Simple routing methods |
| Middleware | Complex to implement | Built-in middleware support |
| Development Speed | Slower | Faster |
Key Characteristics
- Fast: Optimized request handling and efficient routing.
- Unopinionated: Developer has freedom to structure code (no enforced MVC).
- Minimalistic: Built-in methods like
res.json()andres.send()reduce boilerplate.
2. Project Structure & Setup
package.json configuration
Thepackage.json file manages your project’s dependencies and metadata.
| Type | Purpose | Production |
|---|---|---|
| dependencies | Required to run the app (e.g., express, mongoose) | ✅ Installed |
| devDependencies | Only for development (e.g., nodemon, jest) | ❌ Not installed |
3. HTTP Methods & CRUD Operations
| Method | CRUD | Purpose | Idempotent? |
|---|---|---|---|
| GET | Read | Fetch/retrieve data | ✅ Yes |
| POST | Create | Create new resource | ❌ No |
| PUT | Update | Replace entire resource | ✅ Yes |
| PATCH | Update | Update partial resource | ✅ Yes |
| DELETE | Delete | Remove resource | ✅ Yes |
PUT vs PATCH
- PUT: Replaces the entire document. If fields are missing in the request, they may be removed if not handled.
- PATCH: Updates only the specified fields, preserving the rest of the document.
4. Request-Response Cycle
The Request Object (req)
Contains all incoming client data:
req.body: Data from POST/PUT/PATCH.req.params: Dynamic segments in URL (e.g.,/users/:id).req.query: Optional filters after?(e.g.,?sort=asc).req.headers: Authentication tokens, content-types.
The Response Object (res)
Used to send data back:
res.status(code): Set HTTP status.res.json(data): Send JSON response.res.send(data): Send plain text/HTML.res.redirect(url): Redirect client.
5. URL Structure & Routing
- Route Parameters (
req.params): Used for required identifiers. - Query Strings (
req.query): Used for optional filters (sorting, pagination).
6. Middleware Architecture
Middleware are functions that execute between the request and the response. They follow a chain pattern.Types of Middleware
- Application-level:
app.use() - Router-level:
router.use() - Built-in:
express.json(),express.static() - Third-party:
cors(),morgan(),helmet() - Error-handling: Middleware with 4 arguments
(err, req, res, next)
7. Interview Questions & Answers
1. What is middleware in Express.js?
1. What is middleware in Express.js?
Answer:
Middleware functions are functions that have access to the request object (
req), the response object (res), and the next middleware function in the application’s request-response cycle. They can:- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
next() to pass control to the next middleware function. Otherwise, the request will be left hanging.2. Difference between req.params and req.query?
2. Difference between req.params and req.query?
Answer:
- req.params: Extracted from the URL path defined by placeholders like
/:userId. They are used for identifying a specific resource (e.g.,/users/123). - req.query: Extracted from the query string after the
?. They are used for filtering or modifying the result of a request (e.g.,/users?sort=desc).
3. How do you handle errors in Express?
3. How do you handle errors in Express?
Answer:
Errors are handled using special Error-handling middleware. Unlike regular middleware, these have four arguments: In asynchronous code, you must pass errors to
(err, req, res, next).next(err) to trigger this middleware.4. What is express.json() and why is it needed?
4. What is express.json() and why is it needed?
Answer:
It is a built-in middleware function in Express that parses incoming requests with JSON payloads. It is based on the
body-parser library. Without it, your application won’t be able to read data sent in the request body via req.body (it will be undefined).5. Explain the execution order of code below
5. Explain the execution order of code below
/, the output will be A followed by B. The request first hits the application-level middleware (A), calls next(), then proceeds to the route handler (B).