Express is the most popular Node.js web framework. It provides a thin layer of features on top of Node's built-in http module, making it fast and straightforward to build web applications and APIs.
Installing Express
Start a new project and install Express:
mkdir my-api && cd my-api
npm init -y
npm install express
npm install -D nodemonAdd a dev script to package.json:
{
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
}
}Your First Express Server
Run it with npm run dev and visit http://localhost:3000 in your browser.
Understanding Request and Response
Every route handler receives req (request) and res (response) objects.
The Request Object
The Response Object
| Method | Use For |
|---|---|
res.json() | Send JSON data |
res.send() | Send string, buffer, or object |
res.status() | Set HTTP status code |
res.redirect() | Redirect to another URL |
res.set() | Set response headers |
Parsing Request Bodies
Express does not parse request bodies by default. Add the built-in middleware:
Project Structure
Organize your code as the project grows:
my-api/
├── src/
│ ├── app.js # Express app setup
│ ├── server.js # Server startup
│ ├── routes/
│ │ ├── users.js # User routes
│ │ └── posts.js # Post routes
│ ├── controllers/
│ │ ├── userController.js
│ │ └── postController.js
│ ├── middleware/
│ │ ├── auth.js
│ │ └── errorHandler.js
│ └── config/
│ └── index.js # Configuration
├── package.json
└── .envSeparating App and Server
This separation makes your app easier to test because you can import app without starting the server.
Route Organization
Extract routes into separate files:
Configuration Module
Centralize your configuration:
Error Handling
Add a global error handler:
Register it after all routes:
Practical Exercise
Set up a complete Express project with proper structure:
Key Takeaways
- Express adds routing, middleware, and convenience methods on top of Node's
httpmodule. - Use
express.json()middleware to parse JSON request bodies. - Separate your app setup from server startup for testability.
- Organize routes into separate files using
express.Router(). - Always add a global error handler as the last middleware.