Getting Started
Express.js is a minimal and flexible Node.js web application framework that provides robust features for web and mobile applications.
Basic Setup
javascript
import express from 'express';
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
app.listen(3000);Routing
Express provides a powerful routing system.
RESTful Routes
javascript
// GET all users
app.get('/api/users', async (req, res) => {
const users = await User.find();
res.json(users);
});
// GET single user
app.get('/api/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// POST new user
app.post('/api/users', async (req, res) => {
const user = await User.create(req.body);
res.status(201).json(user);
});
// PUT update user
app.put('/api/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
res.json(user);
});
// DELETE user
app.delete('/api/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.status(204).send();
});Middleware
Middleware functions have access to req, res, and next.
Application-Level Middleware
javascript
// Logger middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// Authentication middleware
app.use('/api/protected', (req, res, next) => {
if (req.headers.authorization) {
next();
} else {
res.status(401).json({ error: 'Unauthorized' });
}
});Error Handling Middleware
javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
error: 'Something went wrong!',
message: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});Best Practices
- 1Use router modules: Organize routes by feature
- 2Validate input: Use validation middleware
- 3Secure your app: Helmet, CORS, rate limiting
- 4Handle errors: Never let errors crash your app
- 5Use async/await: Modern async patterns
Project Structure
src/
├── routes/
│ ├── auth.js
│ ├── users.js
│ └── posts.js
├── middleware/
│ ├── auth.js
│ ├── validation.js
│ └── errorHandler.js
├── controllers/
├── models/
└── app.jsConclusion
Express.js provides a solid foundation for building web applications. Follow these patterns to build maintainable, scalable applications.