Express.js Projects


Beginners To Experts


The site is under development.

ExpressJS Questions

Explanation:

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It simplifies the process of building server-side applications by providing an easy way to handle routing, middleware, and HTTP requests/responses.

Using Express.js speeds up development with its middleware architecture, supports RESTful APIs, and has a large ecosystem.

Example Code:

// Import the Express module
const express = require('express');

// Create an Express application instance
const app = express();

// Define a route handler for GET requests to root URL ('/')
app.get('/', (req, res) => {
  // Send "Hello World" as response
  res.send('Hello World');
});

// Start server on port 3000 and log a message when ready
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
      

Explanation:

To use Express.js, you first need Node.js installed. Then, in your project folder, you initialize npm and install Express as a dependency using npm or yarn.

Commands to run in terminal:

// Initialize npm project (creates package.json)
npm init -y

// Install Express.js and save as dependency
npm install express
      

After installation, Express can be required and used in your JavaScript files.

Explanation:

A basic Express server listens on a port for incoming requests and sends responses. You create an Express app, define routes to handle requests, and start listening on a specific port.

Example Code:

// Import express
const express = require('express');

// Create app
const app = express();

// Define route for root '/'
app.get('/', (req, res) => {
  res.send('Welcome to Basic Express Server');
});

// Listen on port 3000
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
      

Explanation:

Middleware functions are functions that have access to the request object (req), response object (res), and the next middleware function in the application’s request-response cycle. Middleware can execute code, modify req/res, end the request, or call next() to pass control.

They are used for logging, authentication, parsing request bodies, error handling, etc.

Example Code:

// Import express
const express = require('express');
const app = express();

// Middleware function to log requests
function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next(); // Pass to next middleware/route handler
}

app.use(logger); // Use middleware globally

app.get('/', (req, res) => {
  res.send('Middleware example');
});

app.listen(3000);
      

Explanation:

To handle POST requests, you use app.post() method and parse the request body using built-in middleware like express.json() or express.urlencoded().

Example Code:

// Import express
const express = require('express');
const app = express();

// Middleware to parse JSON body
app.use(express.json());

// POST route handler
app.post('/submit', (req, res) => {
  // Access JSON data sent by client
  const data = req.body;
  res.send(`Data received: ${JSON.stringify(data)}`);
});

app.listen(3000);
      

Explanation:

Express provides a built-in middleware express.static() to serve static assets like HTML, CSS, JS, images from a directory.

Example Code:

// Import express and path
const express = require('express');
const path = require('path');

const app = express();

// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000);
      

Now any file inside 'public' folder can be accessed via URL directly.

Explanation:

Routing refers to how an application’s endpoints (URIs) respond to client requests. Express routes define a path and the HTTP method (GET, POST, etc.) that the app responds to.

Example Code:

// Import express
const express = require('express');
const app = express();

// Define GET route for '/users'
app.get('/users', (req, res) => {
  res.send('User list');
});

// Define POST route for '/users'
app.post('/users', (req, res) => {
  res.send('Create user');
});

app.listen(3000);
      

Explanation:

Route parameters are named URL segments that capture values and make them available via req.params.

Example Code:

// Import express
const express = require('express');
const app = express();

// Define route with parameter ':id'
app.get('/users/:id', (req, res) => {
  // Access parameter value
  const userId = req.params.id;
  res.send(`User ID requested: ${userId}`);
});

app.listen(3000);
      

Explanation:

express.Router() creates modular route handlers which can be mounted as middleware. It helps organize routes by grouping them.

Example Code:

// Import express
const express = require('express');
const app = express();

// Create router instance
const router = express.Router();

// Define routes on router
router.get('/', (req, res) => {
  res.send('Router root');
});

router.get('/about', (req, res) => {
  res.send('Router about');
});

// Mount router on /info path
app.use('/info', router);

app.listen(3000);
      

Explanation:

Express provides error-handling middleware, a function with four arguments (err, req, res, next), to catch and handle errors globally.

Example Code:

// Import express
const express = require('express');
const app = express();

// Route that throws an error
app.get('/', (req, res) => {
  throw new Error('Something went wrong!');
});

// Error-handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Internal Server Error');
});

app.listen(3000);
      

Explanation:

This project demonstrates a basic Express.js app connected to MongoDB using Mongoose. It supports CRUD (Create, Read, Update, Delete) operations on a simple "Item" model.


// Import modules
const express = require('express');
const mongoose = require('mongoose');

const app = express();

// Middleware to parse JSON bodies
app.use(express.json());

// Connect to MongoDB database
mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });

// Define Item schema and model
const itemSchema = new mongoose.Schema({
  name: String,
  quantity: Number
});
const Item = mongoose.model('Item', itemSchema);

// Create - Add new item
app.post('/items', async (req, res) => {
  const newItem = new Item(req.body);
  await newItem.save();
  res.status(201).send(newItem);
});

// Read - Get all items
app.get('/items', async (req, res) => {
  const items = await Item.find();
  res.send(items);
});

// Update - Update item by id
app.put('/items/:id', async (req, res) => {
  const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
  res.send(updatedItem);
});

// Delete - Remove item by id
app.delete('/items/:id', async (req, res) => {
  await Item.findByIdAndDelete(req.params.id);
  res.send({ message: 'Item deleted' });
});

app.listen(3000, () => {
  console.log('CRUD server running on port 3000');
});
      

Explanation:

Implements user signup and login using Express, storing passwords securely by hashing them with bcrypt.


// Import modules
const express = require('express');
const bcrypt = require('bcrypt');

const app = express();
app.use(express.json());

// In-memory user store (replace with DB in real apps)
const users = [];

// Registration endpoint
app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  // Hash password with salt rounds = 10
  const hashedPassword = await bcrypt.hash(password, 10);
  users.push({ username, password: hashedPassword });
  res.status(201).send('User registered');
});

// Login endpoint
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username);
  if (!user) return res.status(400).send('User not found');

  // Compare plaintext password with hashed
  const valid = await bcrypt.compare(password, user.password);
  if (!valid) return res.status(401).send('Invalid password');

  res.send('Login successful');
});

app.listen(3000, () => {
  console.log('Auth server running on port 3000');
});
      

Explanation:

Organizes routes into separate router modules for cleaner, modular code.


// userRoutes.js file
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('User list');
});

router.get('/:id', (req, res) => {
  res.send(`User ${req.params.id} profile`);
});

module.exports = router;

// main app file
const express = require('express');
const userRoutes = require('./userRoutes');

const app = express();

app.use('/users', userRoutes);

app.listen(3000);
      

Explanation:

Implements stateless authentication with JSON Web Tokens (JWT). Users get a token after login, which is required for protected routes.


// Import modules
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const SECRET_KEY = 'secretkey123';

// Login route issues JWT token
app.post('/login', (req, res) => {
  // In real apps, validate user credentials here
  const user = { id: 1, username: 'user' };

  const token = jwt.sign(user, SECRET_KEY, { expiresIn: '1h' });
  res.json({ token });
});

// Middleware to verify JWT token
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

// Protected route
app.get('/dashboard', authenticateToken, (req, res) => {
  res.send(`Welcome ${req.user.username} to your dashboard`);
});

app.listen(3000);
      

Explanation:

Enables Cross-Origin Resource Sharing (CORS) so clients from other origins can access the API.


// Import modules
const express = require('express');
const cors = require('cors');

const app = express();

// Enable CORS for all origins
app.use(cors());

app.get('/', (req, res) => {
  res.send('CORS enabled API');
});

app.listen(3000);
      

Explanation:

Uses multer middleware to handle multipart/form-data for file uploads.


// Import modules
const express = require('express');
const multer = require('multer');

const app = express();

// Configure multer for file storage in uploads folder
const upload = multer({ dest: 'uploads/' });

// Upload endpoint accepts single file with name 'file'
app.post('/upload', upload.single('file'), (req, res) => {
  // File info is available on req.file
  res.send(`File ${req.file.originalname} uploaded successfully`);
});

app.listen(3000);
      

Explanation:

Implements data pagination using query parameters page and limit.


// Import express
const express = require('express');
const app = express();

// Sample data array
const items = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` }));

app.get('/items', (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;

  const startIndex = (page - 1) * limit;
  const pagedItems = items.slice(startIndex, startIndex + limit);

  res.json({
    page,
    limit,
    totalItems: items.length,
    totalPages: Math.ceil(items.length / limit),
    data: pagedItems
  });
});

app.listen(3000);
      

Explanation:

Uses express-rate-limit to limit repeated requests to APIs to prevent abuse.


// Import modules
const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();

// Configure rate limiter: max 10 requests per minute per IP
const limiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 10,
  message: 'Too many requests, please try again later.'
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limited API');
});

app.listen(3000);
      

Explanation:

Sets up an HTTPS server using Express with SSL certificates.


// Import modules
const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

app.get('/', (req, res) => {
  res.send('Secure HTTPS server');
});

// Load SSL certificates
const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

// Create HTTPS server
https.createServer(options, app).listen(3443, () => {
  console.log('HTTPS server running on port 3443');
});
      

Explanation:

Adds real-time bidirectional communication using socket.io with Express.


// Import modules
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on('connection', (socket) => {
  console.log('a user connected');

  // Listen for chat message from client
  socket.on('chat message', (msg) => {
    // Broadcast message to all clients
    io.emit('chat message', msg);
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

app.get('/', (req, res) => {
  res.send('Socket.io server running');
});

server.listen(3000);
      

Explanation:

This project demonstrates how to build a simple REST API with Express.js supporting GET, POST, PUT, and DELETE methods.


// Import Express
const express = require('express');
const app = express();

// Middleware to parse JSON body
app.use(express.json());

// In-memory storage for resources
let books = [];

// GET all books
app.get('/books', (req, res) => {
  res.json(books);
});

// POST new book
app.post('/books', (req, res) => {
  const book = req.body;
  books.push(book);
  res.status(201).json(book);
});

// PUT update a book by id
app.put('/books/:id', (req, res) => {
  const id = req.params.id;
  const index = books.findIndex(b => b.id == id);
  if (index !== -1) {
    books[index] = req.body;
    res.json(books[index]);
  } else {
    res.status(404).send('Book not found');
  }
});

// DELETE a book by id
app.delete('/books/:id', (req, res) => {
  const id = req.params.id;
  books = books.filter(b => b.id != id);
  res.send('Book deleted');
});

app.listen(3000, () => {
  console.log('REST API running on port 3000');
});
      

Explanation:

Create a custom middleware function that logs request details (method, URL, and timestamp) to the console for every request.


// Import express
const express = require('express');
const app = express();

// Logger middleware function
function logger(req, res, next) {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next(); // Continue to next middleware or route
}

// Use logger middleware globally
app.use(logger);

// Sample route
app.get('/', (req, res) => {
  res.send('Hello from Logger Middleware!');
});

app.listen(3000);
      

Explanation:

Demonstrates how to extract query parameters from the URL in Express and use them to filter or respond.


// Import express
const express = require('express');
const app = express();

// Sample data
const products = [
  { id: 1, name: 'Book', category: 'education' },
  { id: 2, name: 'Pen', category: 'stationery' },
  { id: 3, name: 'Notebook', category: 'education' }
];

// Route with query parameter filtering
app.get('/products', (req, res) => {
  const category = req.query.category;
  if (category) {
    const filtered = products.filter(p => p.category === category);
    res.json(filtered);
  } else {
    res.json(products);
  }
});

app.listen(3000);
      

Explanation:

Use Express to serve static HTML files by configuring the express.static middleware.


// Import express and path
const express = require('express');
const path = require('path');

const app = express();

// Serve static files from 'public' folder
app.use(express.static(path.join(__dirname, 'public')));

// Root route to serve index.html automatically from public folder
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(3000);
      

Explanation:

Manage configuration data like ports or database URLs securely by using environment variables with the dotenv package.


// Install dotenv with: npm install dotenv

// Load environment variables
require('dotenv').config();

const express = require('express');
const app = express();

// Use port from env or default to 3000
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send(`Server running on port ${PORT}`);
});

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});
      

.env file example:

PORT=4000
DATABASE_URL=mongodb://localhost:27017/mydb
      

Explanation:

This project shows extracting and using multiple query string parameters.


// Import express
const express = require('express');
const app = express();

app.get('/search', (req, res) => {
  const { term, page = 1 } = req.query;
  res.send(`Search results for: ${term}, page: ${page}`);
});

app.listen(3000);
      

Explanation:

Uses EJS view engine to render dynamic HTML pages with variables passed from Express.


// Install ejs with: npm install ejs

const express = require('express');
const app = express();

// Set EJS as template engine
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  const user = { name: 'Alice', age: 30 };
  res.render('index', { user }); // Pass user object to template
});

app.listen(3000);
      

index.ejs file example:

<!DOCTYPE html>
<html>
<head>
  <title>EJS Example</title>
</head>
<body>
  <h1>Welcome, <%= user.name %>!</h1>
  <p>Your age is <%= user.age %>.</p>
</body>
</html>
      

Explanation:

Manage user sessions with express-session middleware, enabling stateful authentication.


// Install express-session: npm install express-session

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));

app.get('/login', (req, res) => {
  req.session.user = 'Alice'; // Set session data
  res.send('User logged in');
});

app.get('/profile', (req, res) => {
  if (req.session.user) {
    res.send(`Hello ${req.session.user}, this is your profile.`);
  } else {
    res.status(401).send('Please log in first.');
  }
});

app.listen(3000);
      

Explanation:

Use express-validator to validate and sanitize incoming request data before processing.


// Install express-validator: npm install express-validator

const express = require('express');
const { body, validationResult } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/register', [
  // Validate fields
  body('email').isEmail(),
  body('password').isLength({ min: 5 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('User registered successfully');
});

app.listen(3000);
      

Explanation:

Uses multer to handle multiple file uploads at once.


// Import modules
const express = require('express');
const multer = require('multer');

const app = express();
const upload = multer({ dest: 'uploads/' });

// Route to handle multiple files (up to 3)
app.post('/upload-multiple', upload.array('files', 3), (req, res) => {
  // req.files contains array of file info
  res.send(`${req.files.length} files uploaded successfully.`);
});

app.listen(3000);
      

Explanation:

This project uses the express-rate-limit middleware to limit the number of API requests per IP to prevent abuse.


// Import required modules
const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();

// Configure rate limiter: max 5 requests per minute
const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1 minute
  max: 5,
  message: 'Too many requests from this IP, please try again later.'
});

// Apply rate limiter to all requests
app.use(limiter);

app.get('/', (req, res) => {
  res.send('Welcome to the rate-limited API!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
      

Explanation:

Demonstrates how to send emails using the Nodemailer package in an Express app.


// Import modules
const express = require('express');
const nodemailer = require('nodemailer');

const app = express();
app.use(express.json());

// Configure transporter for SMTP (example using Gmail)
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your-email@gmail.com',       // replace with your email
    pass: 'your-email-password'         // replace with your password or app password
  }
});

// POST route to send email
app.post('/send-email', (req, res) => {
  const { to, subject, text } = req.body;

  const mailOptions = {
    from: 'your-email@gmail.com',
    to,
    subject,
    text
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).send(error.toString());
    }
    res.send('Email sent: ' + info.response);
  });
});

app.listen(3000);
      

Explanation:

Shows how to send files for download using Express's res.download() method.


// Import modules
const express = require('express');
const path = require('path');

const app = express();

// Route to download a file
app.get('/download', (req, res) => {
  const file = path.join(__dirname, 'files', 'example.pdf'); // Path to file
  res.download(file, 'MyExample.pdf', (err) => {
    if (err) {
      res.status(500).send('Error downloading file');
    }
  });
});

app.listen(3000);
      

Explanation:

Demonstrates how to set and read cookies in Express using the cookie-parser middleware.


// Install cookie-parser: npm install cookie-parser

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

// Route to set cookie
app.get('/set-cookie', (req, res) => {
  res.cookie('username', 'Alice', { maxAge: 900000, httpOnly: true });
  res.send('Cookie set');
});

// Route to read cookie
app.get('/get-cookie', (req, res) => {
  const username = req.cookies.username;
  res.send(`Cookie value: ${username}`);
});

app.listen(3000);
      

Explanation:

Adds middleware to catch all unhandled routes and respond with a 404 Not Found page.


// Import express
const express = require('express');
const app = express();

// Example route
app.get('/', (req, res) => {
  res.send('Welcome to the homepage');
});

// 404 middleware - must be last route
app.use((req, res) => {
  res.status(404).send('404: Page not found');
});

app.listen(3000);
      

Explanation:

Sends JSON formatted data in response to API requests.


// Import express
const express = require('express');
const app = express();

app.get('/api/data', (req, res) => {
  const data = { id: 1, name: 'Sample Data', status: 'OK' };
  res.json(data); // Sends JSON response
});

app.listen(3000);
      

Explanation:

Demonstrates how to redirect users from one route to another.


// Import express
const express = require('express');
const app = express();

app.get('/old-route', (req, res) => {
  // Redirect to new route
  res.redirect('/new-route');
});

app.get('/new-route', (req, res) => {
  res.send('Welcome to the new route!');
});

app.listen(3000);
      

Explanation:

Extracts URL parameters from requests and uses them in response.


// Import express
const express = require('express');
const app = express();

app.get('/users/:userId/books/:bookId', (req, res) => {
  const { userId, bookId } = req.params;
  res.send(`User ID: ${userId}, Book ID: ${bookId}`);
});

app.listen(3000);
      

Explanation:

Reads a local JSON file and sends its contents as a response.


// Import modules
const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();

app.get('/data', (req, res) => {
  const filePath = path.join(__dirname, 'data.json');
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      res.status(500).send('Error reading data file');
      return;
    }
    res.type('json').send(data);
  });
});

app.listen(3000);
      

Explanation:

Implements centralized error handling with Express error middleware to catch errors and send appropriate responses.


// Import express
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  throw new Error('Something failed!');
});

// Error handling middleware (must have 4 params)
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Internal Server Error: ' + err.message);
});

app.listen(3000);
      

Explanation:

Implements simple Basic HTTP Authentication by validating the Authorization header.


// Import express and Buffer
const express = require('express');
const app = express();

// Middleware for Basic Auth
function basicAuth(req, res, next) {
  const auth = req.headers.authorization;
  if (!auth) {
    res.set('WWW-Authenticate', 'Basic realm="401"');
    return res.status(401).send('Authentication required.');
  }
  const b64auth = auth.split(' ')[1];
  const [user, pass] = Buffer.from(b64auth, 'base64').toString().split(':');

  if (user === 'admin' && pass === 'password123') {
    return next();
  }
  res.set('WWW-Authenticate', 'Basic realm="401"');
  res.status(401).send('Authentication failed.');
}

// Protect route with basicAuth middleware
app.get('/secret', basicAuth, (req, res) => {
  res.send('Welcome to the secret area!');
});

app.listen(3000);
      

Explanation:

Enables Cross-Origin Resource Sharing (CORS) in your Express app using the cors package.


// Install cors: npm install cors

const express = require('express');
const cors = require('cors');
const app = express();

// Enable CORS for all routes
app.use(cors());

app.get('/data', (req, res) => {
  res.json({ message: 'This is CORS-enabled for all origins.' });
});

app.listen(3000);
      

Explanation:

Implements token-based authentication using JSON Web Tokens (JWT).


// Install jsonwebtoken: npm install jsonwebtoken

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const SECRET = 'your_jwt_secret';

// Login route to generate token
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  // Dummy check
  if (username === 'user' && password === 'pass') {
    const token = jwt.sign({ username }, SECRET, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).send('Invalid credentials');
  }
});

// Middleware to verify token
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

// Protected route
app.get('/protected', authenticateToken, (req, res) => {
  res.send(`Hello ${req.user.username}, this is a protected route.`);
});

app.listen(3000);
      

Explanation:

Adds security headers to your Express app to protect against common vulnerabilities using Helmet.


// Install helmet: npm install helmet

const express = require('express');
const helmet = require('helmet');

const app = express();

// Use helmet middleware for security headers
app.use(helmet());

app.get('/', (req, res) => {
  res.send('Helmet is protecting this app!');
});

app.listen(3000);
      

Explanation:

Uses Morgan middleware to log HTTP requests in a predefined format.


// Install morgan: npm install morgan

const express = require('express');
const morgan = require('morgan');

const app = express();

// Use morgan to log requests in 'combined' format
app.use(morgan('combined'));

app.get('/', (req, res) => {
  res.send('Morgan is logging requests!');
});

app.listen(3000);
      

Explanation:

Implements distributed rate limiting using Redis as a store, useful for clustered environments.


// Install required packages:
// npm install express rate-limit-redis redis express-rate-limit

const express = require('express');
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const redis = require('redis');

const app = express();

const redisClient = redis.createClient();

// Create rate limiter using Redis store
const limiter = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.sendCommand(args),
  }),
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests, please try again later.'
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limiting with Redis enabled!');
});

app.listen(3000);
      

Explanation:

Demonstrates single file upload handling using multer middleware.


// Install multer: npm install multer

const express = require('express');
const multer = require('multer');

const app = express();

// Configure storage destination
const upload = multer({ dest: 'uploads/' });

// POST route to upload single file
app.post('/upload', upload.single('file'), (req, res) => {
  console.log(req.file); // Info about uploaded file
  res.send('File uploaded successfully.');
});

app.listen(3000);
      

Explanation:

Uses compression middleware to gzip HTTP responses, improving performance.


// Install compression: npm install compression

const express = require('express');
const compression = require('compression');

const app = express();

// Enable compression middleware globally
app.use(compression());

app.get('/', (req, res) => {
  const largeText = 'Hello World! '.repeat(1000);
  res.send(largeText);
});

app.listen(3000);
      

Explanation:

Implements a basic IP blacklist to block certain clients from accessing the API.


// Import express
const express = require('express');
const app = express();

// Blacklist of IP addresses
const blacklist = ['123.456.789.0', '111.222.333.444'];

// Middleware to block blacklisted IPs
app.use((req, res, next) => {
  const ip = req.ip;
  if (blacklist.includes(ip)) {
    return res.status(403).send('Access denied');
  }
  next();
});

app.get('/', (req, res) => {
  res.send('Hello, your IP is not blacklisted!');
});

app.listen(3000);
      

Explanation:

Adds a basic health check route to verify that the server is running.


// Import express
const express = require('express');
const app = express();

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'OK', uptime: process.uptime() });
});

app.listen(3000);
      

Explanation:

Allows only clients with whitelisted IP addresses to access the server.


// Import express
const express = require('express');
const app = express();

// Whitelist of IP addresses
const whitelist = ['::1', '127.0.0.1'];

// Middleware to allow only whitelisted IPs
app.use((req, res, next) => {
  const ip = req.ip;
  if (!whitelist.includes(ip)) {
    return res.status(403).send('Access denied: Your IP is not allowed.');
  }
  next();
});

app.get('/', (req, res) => {
  res.send('Welcome, your IP is whitelisted!');
});

app.listen(3000);
      

Explanation:

Middleware to redirect all HTTP requests to HTTPS for secure connections.


// Import express
const express = require('express');
const app = express();

// Middleware to redirect HTTP to HTTPS
app.use((req, res, next) => {
  if (req.secure || req.headers['x-forwarded-proto'] === 'https') {
    next();
  } else {
    res.redirect('https://' + req.headers.host + req.url);
  }
});

app.get('/', (req, res) => {
  res.send('Secure connection established.');
});

app.listen(3000);
      

Explanation:

Rate limits all clients except those on a whitelist.


// Install express-rate-limit: npm install express-rate-limit

const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();

const whitelist = ['127.0.0.1', '::1'];

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  skip: (req) => whitelist.includes(req.ip),
  message: 'Too many requests'
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limiting with whitelist in effect');
});

app.listen(3000);
      

Explanation:

Handles errors in async route handlers by wrapping them to catch rejections.


// Import express
const express = require('express');
const app = express();

// Helper to catch async errors
const asyncHandler = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get('/async-error', asyncHandler(async (req, res) => {
  // Simulate async error
  throw new Error('Async error occurred!');
}));

// Error middleware
app.use((err, req, res, next) => {
  res.status(500).send('Caught error: ' + err.message);
});

app.listen(3000);
      

Explanation:

Shows how to serve static files from multiple directories in Express.


// Import express and path
const express = require('express');
const path = require('path');

const app = express();

// Serve static files from 'public' folder
app.use(express.static(path.join(__dirname, 'public')));

// Serve static files from 'uploads' folder under /files path
app.use('/files', express.static(path.join(__dirname, 'uploads')));

app.listen(3000);
      

Explanation:

This project demonstrates how to use the express-session middleware to manage user sessions stored in cookies.


// Install express-session: npm install express-session

const express = require('express');
const session = require('express-session');

const app = express();

// Configure session middleware
app.use(session({
  secret: 'keyboard cat',  // Secret key to sign session ID cookie
  resave: false,           // Prevent session resave if unmodified
  saveUninitialized: true // Save uninitialized sessions
}));

// Route to set session data
app.get('/login', (req, res) => {
  req.session.user = 'JohnDoe'; // Store user in session
  res.send('User logged in and session started.');
});

// Route to access session data
app.get('/dashboard', (req, res) => {
  if (req.session.user) {
    res.send(`Welcome, ${req.session.user}`);
  } else {
    res.send('Please login first.');
  }
});

app.listen(3000);
      

Explanation:

Implements local username/password authentication using Passport.js middleware.


// Install: passport, passport-local, express-session

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Dummy user data
const users = [{ id: 1, username: 'user', password: 'pass' }];

// Configure local strategy
passport.use(new LocalStrategy((username, password, done) => {
  const user = users.find(u => u.username === username && u.password === password);
  if (!user) return done(null, false, { message: 'Incorrect credentials.' });
  return done(null, user);
}));

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
  const user = users.find(u => u.id === id);
  done(null, user);
});

// Login route
app.post('/login', passport.authenticate('local', {
  successRedirect: '/profile',
  failureRedirect: '/login'
}));

// Protected route
app.get('/profile', (req, res) => {
  if (req.isAuthenticated()) {
    res.send(`Hello, ${req.user.username}`);
  } else {
    res.redirect('/login');
  }
});

app.listen(3000);
      

Explanation:

Demonstrates rendering HTML views using the EJS template engine in Express.


// Install ejs: npm install ejs

const express = require('express');
const app = express();

// Set view engine to ejs
app.set('view engine', 'ejs');

// Route to render view
app.get('/', (req, res) => {
  const data = { title: 'Welcome', message: 'Hello from EJS!' };
  res.render('index', data);
});

app.listen(3000);
      

Note: Create a folder named views with a file index.ejs containing:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title><%= title %></title>
</head>
<body>
  <h1><%= message %></h1>
</body>
</html>

Explanation:

Uses express-validator to validate and sanitize incoming POST request data.


// Install express-validator: npm install express-validator

const express = require('express');
const { body, validationResult } = require('express-validator');

const app = express();
app.use(express.json());

// Validation middleware
const userValidation = [
  body('email').isEmail().withMessage('Enter a valid email'),
  body('password').isLength({ min: 5 }).withMessage('Password must be at least 5 chars long')
];

// POST route with validation
app.post('/register', userValidation, (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('User data is valid!');
});

app.listen(3000);
      

Explanation:

Serves a SPA and redirects all unknown routes to index.html for client-side routing support.


// Import express and path
const express = require('express');
const path = require('path');

const app = express();

// Serve static files from 'dist' folder (your SPA build output)
app.use(express.static(path.join(__dirname, 'dist')));

// Fallback route to index.html for SPA client-side routing
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(3000);
      

Explanation:

This project streams real-time updates from server to client using SSE.


const express = require('express');
const app = express();

app.get('/events', (req, res) => {
  res.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive'
  });

  let count = 0;
  const interval = setInterval(() => {
    count++;
    res.write(`data: Message number ${count}\n\n`);

    if (count === 10) {
      clearInterval(interval);
      res.end();
    }
  }, 1000);

  req.on('close', () => {
    clearInterval(interval);
  });
});

app.listen(3000);
      

Explanation:

Illustrates creating a custom store for express-rate-limit.


// Install express-rate-limit: npm install express-rate-limit

const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();

// Simple in-memory store for demonstration
const store = {
  hits: {},
  increment(key, cb) {
    this.hits[key] = (this.hits[key] || 0) + 1;
    cb(null, this.hits[key], 1);
  },
  decrement(key) {
    if (this.hits[key]) this.hits[key]--;
  },
  resetKey(key) {
    delete this.hits[key];
  }
};

const limiter = rateLimit({
  windowMs: 60000,
  max:   5,
  store: {
    increment: (key, cb) => {
      store.increment(key, (err, hits, resetTime) => {
        cb(err, hits, resetTime);
      });
    },
    decrement: (key) => {
      store.decrement(key);
    },
    resetKey: (key) => {
      store.resetKey(key);
    }
  }
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Custom rate limit store in action!');
});

app.listen(3000);
      

Explanation:

Implements real-time bidirectional communication between client and server with Socket.IO.


// Install socket.io: npm install socket.io

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  // Listen for chat messages from clients
  socket.on('chat message', (msg) => {
    // Broadcast message to all connected clients
    io.emit('chat message', msg);
  });

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

server.listen(3000);
      

Explanation:

Implements rate limiting with express-rate-limit using the default in-memory store.


// Install express-rate-limit: npm install express-rate-limit

const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();

// Configure rate limiter: max 10 requests per 10 minutes
const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 minutes
  max: 10,
  message: 'Too many requests from this IP, please try again later.'
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limiting with default memory store');
});

app.listen(3000);
      

Explanation:

Sends emails from an Express server using Nodemailer package.


// Install nodemailer: npm install nodemailer

const express = require('express');
const nodemailer = require('nodemailer');

const app = express();
app.use(express.json());

// Configure transporter with SMTP settings
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false, // true for 465, false for other ports
  auth: {
    user: 'user@example.com',
    pass: 'yourpassword'
  }
});

app.post('/send-email', async (req, res) => {
  const { to, subject, text } = req.body;
  try {
    const info = await transporter.sendMail({
      from: '"Sender Name" ',
      to,
      subject,
      text
    });
    res.send('Email sent: ' + info.messageId);
  } catch (error) {
    res.status(500).send('Error sending email: ' + error.message);
  }
});

app.listen(3000);
      

Explanation:

Shows how to implement rate limiting using a Redis cluster for distributed environments.


// This example assumes Redis Cluster is set up separately.

const express = require('express');
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const Redis = require('ioredis');

const app = express();

const redisClient = new Redis.Cluster([
  { host: '127.0.0.1', port: 7000 },
  { host: '127.0.0.1', port: 7001 },
  // Add your Redis cluster nodes here
]);

const limiter = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.call(...args),
  }),
  windowMs: 15 * 60 * 1000,
  max: 100,
  message: 'Too many requests, try again later.'
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limiting with Redis cluster store enabled');
});

app.listen(3000);
      

Explanation:

Sets up a GraphQL API server on Express using Apollo Server.


// Install packages:
// npm install express apollo-server-express graphql

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

const app = express();

// Define GraphQL schema
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Define resolvers
const resolvers = {
  Query: {
    hello: () => 'Hello from GraphQL!'
  }
};

async function startServer() {
  const server = new ApolloServer({ typeDefs, resolvers });
  await server.start();
  server.applyMiddleware({ app });

  app.listen(3000, () => {
    console.log('Server running at http://localhost:3000' + server.graphqlPath);
  });
}

startServer();
      

Explanation:

This example applies rate limiting except for IPs on a whitelist.


// Install express-rate-limit: npm install express-rate-limit

const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();

const whitelist = ['127.0.0.1', '::1'];

const limiter = rateLimit({
  windowMs: 5 * 60 * 1000,
  max: 10,
  skip: (req) => whitelist.includes(req.ip),
  message: 'Too many requests'
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Welcome, rate limiting with whitelist is active!');
});

app.listen(3000);
      

Explanation:

Creates custom middleware that logs details of each incoming request.


const express = require('express');
const app = express();

// Custom logging middleware
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) => {
  res.send('Check your console for logged requests!');
});

app.listen(3000);
      

Explanation:

Demonstrates versioning APIs by using different routes for each version.


const express = require('express');
const app = express();

// Version 1 API route
app.get('/api/v1/users', (req, res) => {
  res.json({ version: 'v1', users: ['Alice', 'Bob'] });
});

// Version 2 API route with extra data
app.get('/api/v2/users', (req, res) => {
  res.json({ version: 'v2', users: [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }] });
});

app.listen(3000);
      

Explanation:

Uses Helmet middleware to set various HTTP headers that improve Express app security.


// Install helmet: npm install helmet

const express = require('express');
const helmet = require('helmet');

const app = express();

// Use helmet to secure Express headers
app.use(helmet());

app.get('/', (req, res) => {
  res.send('Helmet middleware is securing your app!');
});

app.listen(3000);
      

Explanation:

Implements JWT authentication for securing routes with token verification.


// Install jsonwebtoken: npm install jsonwebtoken

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const SECRET_KEY = 'your-secret-key';

// Middleware to verify token
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

// Login route to issue token
app.post('/login', (req, res) => {
  // Dummy user
  const user = { id: 1, name: 'John' };
  const token = jwt.sign(user, SECRET_KEY, { expiresIn: '1h' });
  res.json({ token });
});

// Protected route
app.get('/dashboard', authenticateToken, (req, res) => {
  res.send(`Welcome ${req.user.name}, to your dashboard.`);
});

app.listen(3000);
      

Explanation:

Demonstrates handling file uploads in Express using Multer middleware.


// Install multer: npm install multer

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();

// Configure storage options
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'); // upload folder
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); // unique filename
  }
});

const upload = multer({ storage });

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully: ' + req.file.filename);
});

app.listen(3000);
      

Explanation:

This project shows how to paginate results in a REST API endpoint.


const express = require('express');
const app = express();

// Dummy data array
const items = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);

app.get('/items', (req, res) => {
  const page = parseInt(req.query.page) || 1; // Current page
  const limit = parseInt(req.query.limit) || 10; // Items per page

  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;

  const paginatedItems = items.slice(startIndex, endIndex);

  res.json({
    page,
    limit,
    totalItems: items.length,
    items: paginatedItems
  });
});

app.listen(3000);
      

Explanation:

Enables Cross-Origin Resource Sharing (CORS) in Express apps using the cors package.


// Install cors: npm install cors

const express = require('express');
const cors = require('cors');

const app = express();

// Enable all CORS requests
app.use(cors());

app.get('/', (req, res) => {
  res.send('CORS enabled for all origins!');
});

app.listen(3000);
      

Explanation:

Loads environment variables from a .env file using the dotenv package.


// Install dotenv: npm install dotenv

require('dotenv').config();

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send(`App running in ${process.env.NODE_ENV} mode`);
});

app.listen(process.env.PORT || 3000, () => {
  console.log(`Server started on port ${process.env.PORT}`);
});
      

Note: Create a .env file with:


NODE_ENV=development
PORT=4000

Explanation:

Uses Morgan middleware to log HTTP requests to the console.


// Install morgan: npm install morgan

const express = require('express');
const morgan = require('morgan');

const app = express();

// Use morgan with 'combined' preset format
app.use(morgan('combined'));

app.get('/', (req, res) => {
  res.send('Morgan is logging HTTP requests!');
});

app.listen(3000);
      

Explanation:

Protects API endpoints by limiting the number of requests from a single IP.


// Install express-rate-limit: npm install express-rate-limit

const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP, please try again after 15 minutes.'
});

// Apply rate limiting to API routes only
app.use('/api/', apiLimiter);

app.get('/api/data', (req, res) => {
  res.json({ message: 'This is rate limited data' });
});

app.listen(3000);
      

Explanation:

Uses compression middleware to gzip HTTP responses, improving performance.


// Install compression: npm install compression

const express = require('express');
const compression = require('compression');

const app = express();

// Use compression middleware
app.use(compression());

app.get('/', (req, res) => {
  res.send('Response is compressed!');
});

app.listen(3000);
      

Explanation:

Demonstrates creating a centralized error handling middleware in Express.


const express = require('express');
const app = express();

// Route that triggers an error
app.get('/error', (req, res, next) => {
  const err = new Error('Something went wrong!');
  err.status = 500;
  next(err);
});

// Error handling middleware
app.use((err, req, res, next) => {
  res.status(err.status || 500);
  res.json({
    error: {
      message: err.message
    }
  });
});

app.listen(3000);
      

Explanation:

Adds Cross-Site Request Forgery protection using the csurf package.


// Install csurf: npm install csurf cookie-parser

const express = require('express');
const cookieParser = require('cookie-parser');
const csurf = require('csurf');

const app = express();

app.use(cookieParser());

// Setup CSRF protection middleware
const csrfProtection = csurf({ cookie: true });

app.get('/form', csrfProtection, (req, res) => {
  // Send CSRF token to client
  res.send(`
`); }); app.post('/process', csrfProtection, (req, res) => { res.send('Form processed successfully.'); }); app.listen(3000);

Explanation:

Configures Morgan with a custom logging format to log specific request details.


// Install morgan: npm install morgan

const express = require('express');
const morgan = require('morgan');

const app = express();

// Custom format: method - url - status - response-time ms
app.use(morgan(':method - :url - :status - :response-time ms'));

app.get('/', (req, res) => {
  res.send('Custom Morgan log format active!');
});

app.listen(3000);
      

Explanation:

Sets up an HTTPS server in Express using SSL certificates.


const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

const options = {
  key: fs.readFileSync('./certs/key.pem'),
  cert: fs.readFileSync('./certs/cert.pem')
};

app.get('/', (req, res) => {
  res.send('Secure HTTPS server running');
});

https.createServer(options, app).listen(3443, () => {
  console.log('HTTPS server running on port 3443');
});
      

Note: SSL certificate files must exist at ./certs/key.pem and ./certs/cert.pem.

Explanation:

Integrates WebSocket server using the 'ws' package for real-time communication.


// Install ws: npm install ws

const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', ws => {
  console.log('Client connected');

  ws.on('message', message => {
    console.log('Received:', message);
    // Echo message back
    ws.send(`You said: ${message}`);
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

server.listen(3000);
      

Explanation:

Uses built-in express.static middleware to serve static assets like HTML, CSS, images.


const express = require('express');
const path = require('path');

const app = express();

// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000);
      

Place your static files (index.html, styles.css, images, etc.) inside the public folder.

Explanation:

Demonstrates how to read and set cookies in Express using the cookie-parser middleware.


// Install cookie-parser: npm install cookie-parser

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

// Route to set a cookie
app.get('/set-cookie', (req, res) => {
  res.cookie('username', 'JohnDoe', { httpOnly: true, maxAge: 900000 });
  res.send('Cookie has been set');
});

// Route to read cookie
app.get('/get-cookie', (req, res) => {
  const username = req.cookies.username;
  res.send(`Username cookie value: ${username}`);
});

app.listen(3000);
      

Explanation:

Implements session management to track user data across requests using express-session.


// Install express-session: npm install express-session

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  secret: 'mySecretKey',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 } // 1 minute
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`You visited this page ${req.session.views} times`);
  } else {
    req.session.views = 1;
    res.send('Welcome! This is your first visit.');
  }
});

app.listen(3000);
      

Explanation:

Shows how to respond with JSON data to API requests.


const express = require('express');
const app = express();

app.get('/api/user', (req, res) => {
  res.json({
    id: 1,
    name: 'Alice',
    email: 'alice@example.com'
  });
});

app.listen(3000);
      

Explanation:

Demonstrates redirecting client requests to different routes.


const express = require('express');
const app = express();

app.get('/old-route', (req, res) => {
  // Redirect client to new route
  res.redirect('/new-route');
});

app.get('/new-route', (req, res) => {
  res.send('You have been redirected to the new route!');
});

app.listen(3000);
      

Explanation:

Sends static files like HTML, images, or PDFs in response using Express's sendFile method.


const express = require('express');
const path = require('path');

const app = express();

app.get('/download', (req, res) => {
  const filePath = path.join(__dirname, 'files', 'example.pdf');
  res.sendFile(filePath);
});

app.listen(3000);
      

Explanation:

Shows how to access query string parameters from the URL.


const express = require('express');
const app = express();

app.get('/search', (req, res) => {
  const query = req.query.q; // get 'q' parameter
  res.send(`Search results for: ${query}`);
});

app.listen(3000);
      

Explanation:

Handles dynamic URL segments using route parameters.


const express = require('express');
const app = express();

app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`User profile for user with ID: ${userId}`);
});

app.listen(3000);
      

Explanation:

Shows how to specify HTTP status codes for redirects (e.g., 301 permanent redirect).


const express = require('express');
const app = express();

app.get('/old-page', (req, res) => {
  // Permanent redirect
  res.redirect(301, '/new-page');
});

app.get('/new-page', (req, res) => {
  res.send('This is the new page.');
});

app.listen(3000);
      

Explanation:

Demonstrates sharing data between middleware and route handlers using res.locals.


const express = require('express');
const app = express();

// Middleware to set data on res.locals
app.use((req, res, next) => {
  res.locals.startTime = Date.now();
  next();
});

app.get('/', (req, res) => {
  const responseTime = Date.now() - res.locals.startTime;
  res.send(`Response time: ${responseTime} ms`);
});

app.listen(3000);
      

Explanation:

Uses app.locals to store variables accessible throughout the app lifetime.


const express = require('express');
const app = express();

// Set global data
app.locals.title = 'My Express App';

app.get('/', (req, res) => {
  res.send `Welcome to ${app.locals.title}!`);
});

app.listen(3000);
      

Explanation:

Creates middleware that logs the current timestamp of each incoming request.


const express = require('express');
const app = express();

// Middleware to log request time
app.use((req, res, next) => {
  console.log('Request Time:', new Date().toISOString());
  next();
});

app.get('/', (req, res) => {
  res.send('Check the console for request timestamps.');
});

app.listen(3000);
      

Explanation:

Adds middleware to catch requests to undefined routes and respond with a 404 message.


const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Home page');
});

// 404 handler - must be after all other routes
app.use((req, res, next) => {
  res.status(404).send('404 - Page Not Found');
});

app.listen(3000);
      

Explanation:

Serves a favicon icon to the browser using the serve-favicon package.


// Install serve-favicon: npm install serve-favicon

const express = require('express');
const favicon = require('serve-favicon');
const path = require('path');

const app = express();

// Serve favicon.ico from public directory
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.get('/', (req, res) => {
  res.send('Favicon is being served!');
});

app.listen(3000);
      

Explanation:

Implements a simple in-memory rate limiter to restrict requests per IP.


const express = require('express');
const app = express();

const requests = {};
const LIMIT = 5; // max requests
const WINDOW = 60000; // 1 minute in ms

app.use((req, res, next) => {
  const ip = req.ip;
  if (!requests[ip]) {
    requests[ip] = { count: 1, startTime: Date.now() };
  } else {
    const currentTime = Date.now();
    if (currentTime - requests[ip].startTime < WINDOW) {
      requests[ip].count++;
    } else {
      requests[ip] = { count: 1, startTime: currentTime };
    }
  }

  if (requests[ip].count > LIMIT) {
    return res.status(429).send('Too many requests - try again later');
  }
  next();
});

app.get('/', (req, res) => {
  res.send('Rate limiting in action!');
});

app.listen(3000);
      

Explanation:

Enables clients to download files from the server with proper headers.


const express = require('express');
const path = require('path');

const app = express();

app.get('/download', (req, res) => {
  const file = path.join(__dirname, 'files', 'example.zip');
  res.download(file, 'myDownload.zip', (err) => {
    if (err) {
      res.status(500).send('Error downloading file.');
    }
  });
});

app.listen(3000);