Express.js (opens in a new tab)
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Core Concepts
Middleware π οΈ
- Definition: Functions that have access to the request and response objects
- Chain Processing: Execute in order of definition
- Common Use Cases:
- Authentication
- Body parsing
- CORS handling
- Error handling
- Logging
Routing πΊοΈ
app.get('/users', (req, res) => {
res.json(users);
});
app.post('/users', (req, res) => {
// Create new user
});Request Handling π¦
- Query parameters
- Route parameters
- Request body
- Headers
- Cookies
Database Integration ποΈ
MongoDB (opens in a new tab) with Mongoose (opens in a new tab)
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const User = mongoose.model('User', userSchema);SQL with Sequelize (opens in a new tab)
const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password');
class User extends Model {}
User.init({
name: DataTypes.STRING,
email: DataTypes.STRING
}, { sequelize });Error Handling β οΈ
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});Authentication π
JWT Implementation
const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
// Verify user credentials
const token = jwt.sign({ userId: user.id }, 'secret_key');
res.json({ token });
});Best Practices
Project Structure
project/
βββ controllers/
βββ models/
βββ routes/
βββ middleware/
βββ config/
βββ app.jsSecurity Measures
- Use Helmet.js for security headers
- Implement rate limiting
- Validate input data
- Use CORS properly
- Set secure cookies
Performance Optimization
- Use compression middleware
- Implement caching
- Optimize database queries
- Use async/await properly
Deployment
Production Considerations
- Environment variables
- Process managers (PM2)
- Load balancing
- Monitoring and logging
- SSL/TLS configuration