Express.js Projects


Beginners To Experts


The site is under development.

ExpressJS Questions

Project Explanation:

This is the simplest Express.js app which listens on port 3000 and responds with "Hello World!" to any GET request on the root URL (/).


// Import express module
const express = require('express');
// Create an Express application
const app = express();

// Define a GET route for the root path '/'
app.get('/', (req, res) => {
  // Send the response "Hello World!"
  res.send('Hello World!');
});

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

Project Explanation:

This Express app responds to a GET request with JSON data, showing how to serve API responses instead of HTML or text.


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

// Define a GET route that returns JSON data
app.get('/api/user', (req, res) => {
  // Respond with a JSON object
  res.json({
    name: 'John Doe',
    age: 30,
    email: 'john@example.com'
  });
});

// Start server
app.listen(3000, () => {
  console.log('JSON API running at http://localhost:3000/api/user');
});
      

Project Explanation:

This project demonstrates custom middleware in Express that logs each incoming request's method and URL.


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

// Custom middleware to log request method and URL
app.use((req, res, next) => {
  console.log(`${req.method} request for ${req.url}`);
  next(); // Proceed to next middleware or route handler
});

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

// Start server
app.listen(3000, () => {
  console.log('Logger middleware server running on port 3000');
});
      

Project Explanation:

Demonstrates how to serve static files like HTML, CSS, or images from a folder named 'public'.


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

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

// Example route (optional)
app.get('/', (req, res) => {
  res.send('Static files are served from the public folder!');
});

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

Project Explanation:

This project shows how to handle POST requests and parse JSON body data sent by clients.


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

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

// POST route to receive JSON data
app.post('/submit', (req, res) => {
  const userData = req.body; // Access parsed JSON data
  console.log('Received data:', userData);
  res.json({ message: 'Data received successfully', data: userData });
});

// Start server
app.listen(3000, () => {
  console.log('POST handler running on http://localhost:3000');
});
      

Project Explanation:

Learn how to capture dynamic segments in URL paths using route parameters.


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

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

// Start server
app.listen(3000, () => {
  console.log('Route parameters server on port 3000');
});
      

Project Explanation:

This project explains how to read query parameters from the URL.


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

// Route that reads query parameters
app.get('/search', (req, res) => {
  const query = req.query.q; // Access 'q' query parameter
  res.send(`Search query: ${query}`);
});

// Start server
app.listen(3000, () => {
  console.log('Query string server running on port 3000');
});
      

Project Explanation:

Demonstrates organizing routes using express.Router() for better modularity.


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

// Import user routes from separate file
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);

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

/* routes/users.js */
const express = require('express');
const router = express.Router();

// Route: GET /users/
router.get('/', (req, res) => {
  res.send('List of users');
});

// Route: GET /users/:id
router.get('/:id', (req, res) => {
  res.send(`User with ID: ${req.params.id}`);
});

module.exports = router;
      

Project Explanation:

Shows how to create centralized error handling middleware to catch and respond to errors gracefully.


// Import 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); // Pass error to middleware
});

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

// Start server
app.listen(3000, () => {
  console.log('Error handler server on port 3000');
});
      

Project Explanation:

Demonstrates using the Pug template engine to render dynamic HTML pages from Express.


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

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

// Route that renders a Pug template
app.get('/', (req, res) => {
  res.render('index', { title: 'Welcome', message: 'Hello from Pug!' });
});

// Start server
app.listen(3000, () => {
  console.log('Pug templating server running on port 3000');
});

/* views/index.pug file content:
doctype html
html
  head
    title= title
  body
    h1= message
*/
      

Project Explanation:

This project demonstrates CRUD operations with MongoDB using Mongoose in Express.js, including creating, reading, updating, and deleting users.


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

const app = express();
app.use(express.json()); // Parse JSON bodies

// Connect to MongoDB (replace with your connection string)
mongoose.connect('mongodb://localhost:27017/expressdb', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Define User schema and model
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number
});
const User = mongoose.model('User', userSchema);

// Create a new user (POST /users)
app.post('/users', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Get all users (GET /users)
app.get('/users', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

// Update user by ID (PUT /users/:id)
app.put('/users/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Delete user by ID (DELETE /users/:id)
app.delete('/users/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndDelete(req.params.id);
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json({ message: 'User deleted' });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

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

Project Explanation:

This project shows how to handle file uploads in Express using the Multer middleware, saving uploaded files to a local folder.


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

const app = express();

// Configure multer storage
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'); // Folder to save files
  },
  filename: function (req, file, cb) {
    // Save file with original name and timestamp
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// Single file upload route (input name="file")
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }
  res.send(`File uploaded: ${req.file.filename}`);
});

// Start server
app.listen(3000, () => {
  console.log('File upload server running on port 3000');
});
      

Project Explanation:

Demonstrates how to use express-session middleware for session handling and store user visits count.


// Import modules
const express = require('express');
const session = require('express-session');

const app = express();

// Setup session middleware
app.use(session({
  secret: 'your-secret-key',  // Secret for signing session ID cookie
  resave: false,               // Don't save session if unmodified
  saveUninitialized: true     // Save new sessions
}));

// Route to count visits per user session
app.get('/', (req, res) => {
  if (!req.session.views) {
    req.session.views = 1;
  } else {
    req.session.views++;
  }
  res.send(`Number of visits in this session: ${req.session.views}`);
});

// Start server
app.listen(3000, () => {
  console.log('Session demo server running on port 3000');
});
      

Project Explanation:

Protect your Express app from brute force attacks by limiting repeated requests from the same IP using express-rate-limit.


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

const app = express();

// Configure rate limiter: max 5 requests per minute per IP
const limiter = rateLimit({
  windowMs: 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('Hello! You are within request limits.');
});

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

Project Explanation:

Demonstrates enabling Cross-Origin Resource Sharing (CORS) to allow requests from other domains.


// 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 - you can access this from any domain.');
});

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

Project Explanation:

This project uses EJS as a template engine to render dynamic HTML pages.


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

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

// Define route to render a page with data
app.get('/', (req, res) => {
  const user = { name: 'Alice', age: 25 };
  res.render('index', { user });
});

// Start server
app.listen(3000, () => {
  console.log('EJS template server running on port 3000');
});

/* views/index.ejs file content:


  Welcome
  
    

Hello, <%= user.name %>!

Age: <%= user.age %>

*/

Project Explanation:

This project adds real-time 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);

// Serve static files (optional)
app.use(express.static('public'));

// Socket.io connection event
io.on('connection', (socket) => {
  console.log('A user connected');

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

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

// Start server
server.listen(3000, () => {
  console.log('Socket.io server running on port 3000');
});
      

Project Explanation:

Helmet helps secure Express apps by setting various HTTP headers.


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

const app = express();

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

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

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

Project Explanation:

Use compression middleware to gzip responses and improve performance.


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

const app = express();

// Enable gzip compression for all responses
app.use(compression());

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

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

Project Explanation:

This project shows how to use the dotenv package to load environment variables from a .env file.


// Import modules
const express = require('express');
require('dotenv').config(); // Load .env file

const app = express();

const PORT = process.env.PORT || 3000;
const SECRET_KEY = process.env.SECRET_KEY || 'defaultsecret';

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

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

/* Example .env file:
PORT=5000
SECRET_KEY=mySuperSecretKey
*/
      

Project Explanation:

This project creates a simple paginated API endpoint that returns items by page number and page size.


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

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

// Pagination route: /items?page=1&size=10
app.get('/items', (req, res) => {
  const page = parseInt(req.query.page) || 1;       // Default page 1
  const size = parseInt(req.query.size) || 10;      // Default size 10

  const startIndex = (page - 1) * size;
  const endIndex = startIndex + size;

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

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

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

Project Explanation:

This project uses Redis for distributed rate limiting by IP to limit API abuse.


// Note: Requires Redis server and 'express-rate-limit' and 'rate-limit-redis' packages installed.

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

const app = express();

// Create Redis client
const redisClient = redis.createClient();

const limiter = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.sendCommand(args)
  }),
  windowMs: 60 * 1000, // 1 minute window
  max: 10,             // limit each IP to 10 requests per windowMs
  message: 'Too many requests, slow down!'
});

app.use(limiter);

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

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

Project Explanation:

Implements user login that returns a JWT token, and a protected route that requires the token for access.


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

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

const SECRET_KEY = 'your_jwt_secret_key';

// Dummy user data
const user = { id: 1, username: 'admin', password: 'password' };

// Login route
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (username === user.username && password === user.password) {
    // Generate token with payload
    const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).json({ error: '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.status(401).json({ error: 'Token missing' });

  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) return res.status(403).json({ error: 'Token invalid' });
    req.user = user;
    next();
  });
}

// Protected route
app.get('/protected', authenticateToken, (req, res) => {
  res.json({ message: 'Protected data accessed!', user: req.user });
});

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

Project Explanation:

This project sends emails using the Nodemailer package.


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

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

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

// 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).json({ error: error.toString() });
    }
    res.json({ message: 'Email sent', info });
  });
});

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

Project Explanation:

This example shows how to support multiple API versions in one Express app.


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

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

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

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

Project Explanation:

Demonstrates local authentication strategy with Passport.js in Express.


// Import modules
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 }));

// Configure session middleware
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));

// Initialize passport
app.use(passport.initialize());
app.use(passport.session());

// Dummy user
const user = { id: 1, username: 'admin', password: 'password' };

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

// Serialize user to session
passport.serializeUser((user, done) => done(null, user.id));

// Deserialize user from session
passport.deserializeUser((id, done) => {
  if (id === user.id) return done(null, user);
  done('User not found');
});

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

// Protected route
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) return next();
  res.redirect('/login');
}

app.get('/dashboard', ensureAuthenticated, (req, res) => {
  res.send(`Hello ${req.user.username}, welcome to your dashboard!`);
});

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

Project Explanation:

Sets up Swagger UI to auto-generate API documentation for Express endpoints.


// Import modules
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');

const app = express();

// Swagger definition
const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'Express API',
      version: '1.0.0',
      description: 'Sample API documentation'
    }
  },
  apis: ['./index.js'], // Point to file with Swagger comments
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

/**
 * @swagger
 * /hello:
 *   get:
 *     summary: Returns greeting message
 *     responses:
 *       200:
 *         description: Greeting message
 */
app.get('/hello', (req, res) => {
  res.send('Hello from Swagger documented API!');
});

app.listen(3000, () => {
  console.log('Swagger API docs at http://localhost:3000/api-docs');
});
      

Project Explanation:

Applies rate limiting only to sensitive routes like login to prevent brute-force attacks.


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

const app = express();

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5,                   // limit each IP to 5 requests per windowMs
  message: 'Too many login attempts, please try again later.'
});

app.post('/login', loginLimiter, (req, res) => {
  // Login logic here
  res.send('Login attempt');
});

app.get('/', (req, res) => {
  res.send('No rate limiting here');
});

app.listen(3000, () => {
  console.log('Selective rate limiting server on port 3000');
});
      

Project Explanation:

Adds CSRF protection middleware to protect forms from cross-site request forgery.


// Import modules
const express = require('express');
const cookieParser = require('cookie-parser');
const csrf = require('csurf');

const app = express();

app.use(cookieParser());

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

// Parse urlencoded form bodies
app.use(express.urlencoded({ extended: false }));

// Form route with CSRF token
app.get('/form', csrfProtection, (req, res) => {
  res.send(`
`); }); // Process form POST request with CSRF check app.post('/process', csrfProtection, (req, res) => { res.send('Form data is processed safely.'); }); app.listen(3000, () => { console.log('CSRF protection server running on port 3000'); });

Project Explanation:

Demonstrates centralized error handling middleware to catch errors and send JSON responses.


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

// Sample route that throws error
app.get('/', (req, res, next) => {
  try {
    throw new Error('Something went wrong!');
  } catch (err) {
    next(err); // Pass error to error handler middleware
  }
});

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

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

Project Explanation:

This project demonstrates handling file uploads using Multer middleware in Express.


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

const app = express();

// Configure storage location and filename for uploads
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/'); // Upload folder
  },
  filename: function(req, file, cb) {
    // Use original filename with timestamp prefix to avoid overwriting
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage });

// Serve upload form (simple HTML)
app.get('/', (req, res) => {
  res.send(`
    

`); }); // Handle POST upload request with multer middleware app.post('/upload', upload.single('myFile'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded.'); } res.send(`File uploaded successfully: ${req.file.filename}`); }); app.listen(3000, () => { console.log('File upload server running on port 3000'); });

Project Explanation:

This project adds Helmet middleware to set HTTP headers for improved security.


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

const app = express();

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

app.get('/', (req, res) => {
  res.send('Helmet security headers enabled!');
});

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

Project Explanation:

This project demonstrates enabling Cross-Origin Resource Sharing (CORS) with the cors package.


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

const app = express();

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

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

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

Project Explanation:

This project shows how to proxy API requests to another server using http-proxy-middleware.


// Import modules
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// Proxy /api requests to https://jsonplaceholder.typicode.com
app.use('/api', createProxyMiddleware({
  target: 'https://jsonplaceholder.typicode.com',
  changeOrigin: true,
  pathRewrite: { '^/api': '' } // remove /api prefix when forwarding
}));

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

Project Explanation:

This project implements Server-Sent Events for one-way real-time updates from server to client.


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

// SSE endpoint
app.get('/events', (req, res) => {
  // Set headers for SSE
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  let count = 0;

  // Send event every second
  const intervalId = setInterval(() => {
    count++;
    res.write(`data: Server time: ${new Date().toLocaleTimeString()}, count: ${count}\n\n`);
    if (count >= 10) {
      clearInterval(intervalId);
      res.end();
    }
  }, 1000);

  // Cleanup if client disconnects
  req.on('close', () => {
    clearInterval(intervalId);
  });
});

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

Project Explanation:

This project creates a basic chat server using Express and Socket.io for real-time communication.


// 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);

// Serve a basic page for client
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

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

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

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

server.listen(3000, () => {
  console.log('Socket.io chat server running on port 3000');
});
      

Project Explanation:

This project uses express-rate-limit with default memory store for simple in-memory rate limiting.


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

const app = express();

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

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

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

app.listen(3000, () => {
  console.log('Memory store rate limiting server on port 3000');
});
      

Project Explanation:

This project compresses HTTP responses using compression middleware to improve performance.


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

const app = express();

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

app.get('/', (req, res) => {
  const largeText = 'Hello world! '.repeat(1000); // Large content to compress
  res.send(largeText);
});

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

Project Explanation:

Demonstrates serving static files such as images, CSS, and JS from a public folder in Express.


// Import express
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, () => {
  console.log('Static files server running on port 3000');
});
      

Project Explanation:

This project shows how to use EJS as a templating engine to render dynamic HTML views in Express.


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

const app = express();

// Set view engine to EJS
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

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

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

Project Explanation:

Implements distributed rate limiting using Redis to handle high traffic scenarios across multiple servers.


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

const app = express();

// Create Redis client instance
const redisClient = new Redis();

// Configure rate limiter to use Redis store
const limiter = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.call(...args),
  }),
  windowMs: 60 * 1000, // 1 minute
  max: 20,             // limit each IP to 20 requests per window
  message: 'Too many requests, please slow down!',
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Redis distributed rate limiting is active.');
});

app.listen(3000, () => {
  console.log('Advanced Redis rate limiting server running on port 3000');
});
      

Project Explanation:

This project creates an API that supports pagination and sorting on a sample dataset.


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

// Sample data array
const users = [
  { id: 1, name: 'Alice', age: 30 },
  { id: 2, name: 'Bob', age: 25 },
  { id: 3, name: 'Charlie', age: 35 },
  { id: 4, name: 'David', age: 20 },
  { id: 5, name: 'Eve', age: 28 },
];

// Endpoint with pagination and sorting
app.get('/users', (req, res) => {
  let { page = 1, limit = 2, sortBy = 'id', order = 'asc' } = req.query;
  page = parseInt(page);
  limit = parseInt(limit);

  // Sort users
  const sorted = [...users].sort((a, b) => {
    if (order === 'asc') return a[sortBy] > b[sortBy] ? 1 : -1;
    else return a[sortBy] < b[sortBy] ? 1 : -1;
  });

  // Paginate
  const start = (page - 1) * limit;
  const pagedUsers = sorted.slice(start, start + limit);

  res.json({
    page,
    limit,
    totalUsers: users.length,
    users: pagedUsers,
  });
});

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

Project Explanation:

This project integrates Swagger for API documentation and Joi for request validation.


// Import modules
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const Joi = require('joi');

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

// Swagger config
const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: { title: 'Joi & Swagger API', version: '1.0.0' },
  },
  apis: ['./index.js'],
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

/**
 * @swagger
 * /user:
 *   post:
 *     summary: Create user with validation
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               email:
 *                 type: string
 *             required:
 *               - name
 *               - email
 *     responses:
 *       200:
 *         description: User created successfully
 */
const userSchema = Joi.object({
  name: Joi.string().min(3).required(),
  email: Joi.string().email().required(),
});

app.post('/user', (req, res) => {
  const { error } = userSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });
  res.json({ message: 'User created', data: req.body });
});

app.listen(3000, () => {
  console.log('Swagger & Joi validation API running on port 3000');
});
      

Project Explanation:

Implements rate limiting but allows whitelisted IPs unlimited access.


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

const app = express();

// Whitelist of IPs exempt from rate limiting
const whitelist = ['127.0.0.1', '::1'];

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

app.use(limiter);

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

app.listen(3000, () => {
  console.log('Rate limit with whitelist server on port 3000');
});
      

Project Explanation:

Implements simple in-memory caching for an API endpoint to improve performance.


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

const cache = new Map();

app.get('/time', (req, res) => {
  const key = 'time';

  if (cache.has(key)) {
    // Return cached response
    return res.json({ time: cache.get(key), cached: true });
  }

  // Generate new response
  const currentTime = new Date().toISOString();
  cache.set(key, currentTime);

  // Cache expires after 10 seconds
  setTimeout(() => cache.delete(key), 10 * 1000);

  res.json({ time: currentTime, cached: false });
});

app.listen(3000, () => {
  console.log('In-memory caching API running on port 3000');
});
      

Project Explanation:

Sets up Express with HTTPS using a self-signed SSL certificate for secure communication.


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

const app = express();

// Load self-signed cert and key (generated via openssl)
const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
};

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

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

Project Explanation:

Enables clients to download files hosted on the server using Express.


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

const app = express();

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

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

Project Explanation:

Creates a custom rate limiter store to manage request counts with custom logic.


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

const app = express();

// Simple in-memory custom store
class CustomStore {
  constructor() {
    this.hits = new Map();
  }

  incr(key, cb) {
    const current = this.hits.get(key) || 0;
    this.hits.set(key, current + 1);
    cb(null, this.hits.get(key), 1);
  }

  decrement(key) {
    const current = this.hits.get(key) || 0;
    if (current > 0) this.hits.set(key, current - 1);
  }

  resetKey(key) {
    this.hits.delete(key);
  }
}

const limiter = rateLimit({
  windowMs: 60000,
  max: 5,
  store: new CustomStore(),
  handler: (req, res) => {
    res.status(429).send('Custom store: Too many requests');
  },
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Custom store rate limiting');
});

app.listen(3000, () => {
  console.log('Custom store rate limit server running on port 3000');
});
      

Project Explanation:

Implements user login authentication using JSON Web Tokens (JWT) for secure API access.


// Import modules
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

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

const SECRET = 'supersecretkey';

// Login route to generate token
app.post('/login', (req, res) => {
  const { username, password } = req.body;

  // Simplified user check
  if (username === 'user' && password === 'pass') {
    const token = jwt.sign({ username }, SECRET, { expiresIn: '1h' });
    return res.json({ token });
  }
  res.status(401).json({ message: 'Invalid credentials' });
});

// Middleware to verify token
function authenticate(req, res, next) {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) return res.status(401).send('Access denied, token missing.');

  try {
    const decoded = jwt.verify(token, SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(401).send('Invalid token.');
  }
}

// Protected route example
app.get('/protected', authenticate, (req, res) => {
  res.send(`Hello ${req.user.username}, you accessed protected data!`);
});

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

Project Explanation:

Extends file upload with Multer to validate file type and size before saving.


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

const app = express();

// Multer storage config (in-memory)
const storage = multer.memoryStorage();

// File filter to accept images only
function fileFilter(req, file, cb) {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Only image files allowed!'), false);
  }
}

const upload = multer({
  storage,
  limits: { fileSize: 1 * 1024 * 1024 }, // 1MB limit
  fileFilter,
});

app.get('/', (req, res) => {
  res.send(`
    

`); }); app.post('/upload', upload.single('photo'), (req, res) => { if (!req.file) { return res.status(400).send('No file or invalid file uploaded.'); } res.send(`Uploaded file: ${req.file.originalname} (${req.file.size} bytes)`); }); // Error handling middleware for multer errors app.use((err, req, res, next) => { if (err instanceof multer.MulterError) { return res.status(400).send(`Multer error: ${err.message}`); } else if (err) { return res.status(400).send(err.message); } next(); }); app.listen(3000, () => { console.log('File upload with validation server running on port 3000'); });

Project Explanation:

Implements user authentication using Passport.js with a local strategy (username/password).


// Import modules
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bodyParser = require('body-parser');

const app = express();

// Middleware setup
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'secretkey', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Dummy user store
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);
  if (!user) return done(null, false, { message: 'Incorrect username.' });
  if (user.password !== password) return done(null, false, { message: 'Incorrect password.' });
  return done(null, user);
}));

// Serialize user to session
passport.serializeUser((user, done) => {
  done(null, user.id);
});

// Deserialize user from session
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',
}));

// Profile route - protected
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) return next();
  res.redirect('/login');
}

app.get('/profile', ensureAuthenticated, (req, res) => {
  res.send(`Hello, ${req.user.username}. This is your profile.`);
});

app.get('/login', (req, res) => {
  res.send('
'); }); app.listen(3000, () => { console.log('Passport local auth server running on port 3000'); });

Project Explanation:

Rate limits requests based on the User-Agent header instead of IP address.


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

const app = express();

// Rate limiter keyed by User-Agent header
const limiter = rateLimit({
  windowMs: 60000,
  max: 10,
  keyGenerator: (req) => req.headers['user-agent'] || 'unknown',
  handler: (req, res) => res.status(429).send('Too many requests from this User-Agent'),
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limited by User-Agent');
});

app.listen(3000, () => {
  console.log('User-Agent rate limiting server running on port 3000');
});
      

Project Explanation:

Implements JWT access and refresh tokens to allow token renewal without re-login.


// Import modules
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

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

const ACCESS_SECRET = 'accesssecretkey';
const REFRESH_SECRET = 'refreshsecretkey';

let refreshTokens = [];

// Login - issue access and refresh tokens
app.post('/login', (req, res) => {
  const { username } = req.body;
  const accessToken = jwt.sign({ username }, ACCESS_SECRET, { expiresIn: '15m' });
  const refreshToken = jwt.sign({ username }, REFRESH_SECRET);
  refreshTokens.push(refreshToken);
  res.json({ accessToken, refreshToken });
});

// Token refresh endpoint
app.post('/token', (req, res) => {
  const { token } = req.body;
  if (!token) return res.status(401).send('Refresh token required');
  if (!refreshTokens.includes(token)) return res.status(403).send('Invalid refresh token');

  jwt.verify(token, REFRESH_SECRET, (err, user) => {
    if (err) return res.status(403).send('Invalid token');
    const accessToken = jwt.sign({ username: user.username }, ACCESS_SECRET, { expiresIn: '15m' });
    res.json({ accessToken });
  });
});

// Logout - remove refresh token
app.post('/logout', (req, res) => {
  const { token } = req.body;
  refreshTokens = refreshTokens.filter(t => t !== token);
  res.send('Logged out');
});

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

Project Explanation:

Implements multi-level rate limiting using two different time windows.


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

const app = express();

// Fast limiter: 5 requests per 15 seconds
const fastLimiter = rateLimit({
  windowMs: 15 * 1000,
  max: 5,
  handler: (req, res) => res.status(429).send('Too many requests - fast window'),
});

// Slow limiter: 100 requests per hour
const slowLimiter = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 100,
  handler: (req, res) => res.status(429).send('Too many requests - slow window'),
});

// Apply both limiters
app.use(fastLimiter);
app.use(slowLimiter);

app.get('/', (req, res) => {
  res.send('Multi-window rate limiting active');
});

app.listen(3000, () => {
  console.log('Multi-window rate limiting server running on port 3000');
});
      

Project Explanation:

Demonstrates API versioning by grouping routes with version prefixes.


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

// Version 1 routes
const v1 = express.Router();
v1.get('/users', (req, res) => {
  res.json({ version: 'v1', users: ['Alice', 'Bob'] });
});

// Version 2 routes with updated response
const v2 = express.Router();
v2.get('/users', (req, res) => {
  res.json({ version: 'v2', users: [{ name: 'Alice' }, { name: 'Bob' }] });
});

app.use('/api/v1', v1);
app.use('/api/v2', v2);

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

Project Explanation:

Rate limits users and permanently blocks IPs exceeding limits repeatedly.


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

const app = express();

const blockedIPs = new Set();

const limiter = rateLimit({
  windowMs: 60 * 1000,
  max: 5,
  handler: (req, res) => {
    blockedIPs.add(req.ip); // Add IP to blocked list
    res.status(429).send('Too many requests - You are blocked');
  },
});

// Middleware to block IPs
app.use((req, res, next) => {
  if (blockedIPs.has(req.ip)) {
    return res.status(403).send('Your IP is blocked.');
  }
  next();
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Welcome! You are not blocked.');
});

app.listen(3000, () => {
  console.log('Rate limit with IP blocking server running on port 3000');
});
      

Project Explanation:

Combines GraphQL API with JWT-based authentication to protect queries and mutations.


// Import modules
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const jwt = require('jsonwebtoken');

const SECRET = 'jwtsecretkey';

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

// Define resolvers with auth check
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
    secretData: (parent, args, context) => {
      if (!context.user) throw new Error('Unauthorized');
      return 'Secret information for ' + context.user.username;
    },
  },
};

const app = express();

// Middleware to extract user from JWT
app.use((req, res, next) => {
  const auth = req.headers.authorization || '';
  const token = auth.split(' ')[1];
  if (token) {
    try {
      const user = jwt.verify(token, SECRET);
      req.user = user;
    } catch {
      req.user = null;
    }
  } else {
    req.user = null;
  }
  next();
});

// Apollo Server setup
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({ user: req.user }),
});

async function startServer() {
  await server.start();
  server.applyMiddleware({ app });
}

startServer();

app.listen(4000, () => {
  console.log('GraphQL server with JWT auth running on port 4000');
});
      

Project Explanation:

Handles image uploads and resizes images using Sharp before saving.


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

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

app.post('/upload', upload.single('image'), async (req, res) => {
  if (!req.file) return res.status(400).send('No file uploaded.');

  const outputPath = path.join('uploads', 'resized-' + req.file.filename + '.jpg');

  try {
    // Resize image to 200x200 pixels and save as jpg
    await sharp(req.file.path)
      .resize(200, 200)
      .jpeg()
      .toFile(outputPath);

    // Delete original uploaded file
    fs.unlinkSync(req.file.path);

    res.send(`Image uploaded and resized: ${outputPath}`);
  } catch (err) {
    res.status(500).send('Error processing image');
  }
});

app.listen(3000, () => {
  console.log('Image upload and resize server running on port 3000');
});
      

Project Explanation:

Adds real-time WebSocket notifications to an Express server using socket.io.


// 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);

// Serve simple HTML client
app.get('/', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html>
    <body>
      <h1>WebSocket Notifications</h1>
      <ul id="messages"></ul>
      <script src="/socket.io/socket.io.js"></script>
      <script>
        const socket = io();
        socket.on('notification', msg => {
          const li = document.createElement('li');
          li.textContent = msg;
          document.getElementById('messages').appendChild(li);
        });
      </script>
    </body>
    </html>
  `);
});

// Broadcast notification every 10 seconds
setInterval(() => {
  io.emit('notification', 'This is a real-time notification at ' + new Date().toLocaleTimeString());
}, 10000);

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

Project Explanation:

Secures Express applications by setting various HTTP headers using Helmet middleware.


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

const app = express();

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

app.get('/', (req, res) => {
  res.send('Hello, your app is secured with Helmet headers!');
});

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

Project Explanation:

Implements rate limiting in Express using Redis as the store to persist request counts across servers.


// Import modules
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();

// Configure rate limiter with Redis store
const limiter = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.call(...args),
  }),
  windowMs: 60000, // 1 minute
  max: 10,
  message: 'Too many requests, please try again later.',
});

app.use(limiter);

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

app.listen(3000, () => {
  console.log('Redis store rate limiting server running on port 3000');
});
      

Project Explanation:

Adds CSRF protection middleware to secure forms against Cross-Site Request Forgery attacks.


// Import modules
const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const app = express();

// Middleware setup
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));

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

app.get('/form', csrfProtection, (req, res) => {
  // Send a form with csrf token embedded
  res.send(`
    <form action="/process" method="POST">
      <input type="hidden" name="_csrf" value="${req.csrfToken()}" />
      <input type="text" name="data" />
      <button type="submit">Submit</button>
    </form>
  `);
});

app.post('/process', csrfProtection, (req, res) => {
  res.send('Form data processed safely!');
});

// Error handler for CSRF errors
app.use((err, req, res, next) => {
  if (err.code === 'EBADCSRFTOKEN') {
    return res.status(403).send('CSRF token validation failed');
  }
  next(err);
});

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

Project Explanation:

Adds Swagger UI to document the Express API endpoints interactively.


// Import modules
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');

const app = express();

// Swagger options
const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'Express API',
      version: '1.0.0',
      description: 'API documentation example',
    },
  },
  apis: ['./index.js'], // Path to API docs
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

/**
 * @swagger
 * /hello:
 *   get:
 *     summary: Returns a hello message
 *     responses:
 *       200:
 *         description: Success
 */
app.get('/hello', (req, res) => {
  res.send('Hello from Swagger documented API!');
});

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

Project Explanation:

Implements rate limiting but whitelists specific IP addresses from limits.


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

const app = express();

const whitelist = ['127.0.0.1']; // Whitelisted IPs

const limiter = rateLimit({
  windowMs: 60000,
  max: 5,
  skip: (req) => whitelist.includes(req.ip),
  handler: (req, res) => res.status(429).send('Too many requests'),
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Rate limiting active, except whitelisted IPs');
});

app.listen(3000, () => {
  console.log('Rate limit with whitelist server running on port 3000');
});
      

Project Explanation:

Configures CORS to allow requests only from specific origins.


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

const app = express();

const allowedOrigins = ['http://localhost:3000', 'https://example.com'];

const corsOptions = {
  origin: function(origin, callback){
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
      const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  }
};

app.use(cors(corsOptions));

app.get('/', (req, res) => {
  res.send('CORS configured with allowed origins only.');
});

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

Project Explanation:

Uses express-session to manage user sessions with cookie storage.


// Import modules
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 session
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`Views: ${req.session.views}`);
  } else {
    req.session.views = 1;
    res.send('Welcome, first visit!');
  }
});

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

Project Explanation:

Uses Helmet to set security headers including a strict Content Security Policy.


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

const app = express();

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      objectSrc: ["'none'"],
      upgradeInsecureRequests: [],
    },
  },
}));

app.get('/', (req, res) => {
  res.send('Helmet with CSP enabled!');
});

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

Project Explanation:

Rate limits users and stores blocked IPs in Redis blacklist for persistence.


// Import modules
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();

const blacklistKey = 'blockedIPs';

const limiter = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.call(...args),
  }),
  windowMs: 60 * 1000,
  max: 5,
  handler: async (req, res) => {
    await redisClient.sadd(blacklistKey, req.ip); // Add IP to blacklist set
    res.status(429).send('Too many requests - you are blocked');
  },
});

// Middleware to block blacklisted IPs
app.use(async (req, res, next) => {
  const isBlocked = await redisClient.sismember(blacklistKey, req.ip);
  if (isBlocked) {
    return res.status(403).send('Your IP is blocked.');
  }
  next();
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('Welcome! You are not blocked.');
});

app.listen(3000, () => {
  console.log('Rate limit with Redis blacklist server running on port 3000');
});
      

Project Explanation:

Combines security headers using Helmet with basic IP rate limiting.


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

const app = express();

app.use(helmet());

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

app.use(limiter);

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

app.listen(3000, () => {
  console.log('Helmet + rate limit server running on port 3000');
});
      

Project Explanation:

Combines Helmet security headers, CORS, and gzip compression middleware in Express.


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

const app = express();

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

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

// Use gzip compression for responses
app.use(compression());

app.get('/', (req, res) => {
  res.send('Express app secured, CORS enabled, and compressed!');
});

app.listen(3000, () => {
  console.log('Helmet + CORS + compression server running on port 3000');
});
      

Project Explanation:

Implements OAuth2 Google authentication using Passport.js in Express.


// Import modules
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const session = require('express-session');

const app = express();

// Configure session middleware
app.use(session({ secret: 'secret', resave: false, saveUninitialized: true }));

// Initialize passport
app.use(passport.initialize());
app.use(passport.session());

// Configure Google OAuth strategy
passport.use(new GoogleStrategy({
  clientID: 'YOUR_GOOGLE_CLIENT_ID',
  clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
  callbackURL: '/auth/google/callback',
},
(accessToken, refreshToken, profile, done) => {
  // Here you would save or update user profile in DB
  return done(null, profile);
}));

// Serialize user into session
passport.serializeUser((user, done) => {
  done(null, user);
});

// Deserialize user from session
passport.deserializeUser((obj, done) => {
  done(null, obj);
});

// Routes
app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    res.send(`Welcome, ${req.user.displayName}!`);
  });

app.get('/logout', (req, res) => {
  req.logout(() => {
    res.redirect('/');
  });
});

app.get('/', (req, res) => {
  res.send('Home page. Please login with Google at /auth/google');
});

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

Project Explanation:

Protects API endpoints with API key authentication sent via headers.


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

const app = express();

const VALID_API_KEYS = ['123456789abcdef'];

// Middleware to check API key
app.use((req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey || !VALID_API_KEYS.includes(apiKey)) {
    return res.status(401).send('Unauthorized: Invalid or missing API key');
  }
  next();
});

app.get('/data', (req, res) => {
  res.json({ message: 'Protected data accessed with valid API key' });
});

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

Project Explanation:

Demonstrates MongoDB aggregation pipeline usage via Mongoose in Express.


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

const app = express();

mongoose.connect('mongodb://localhost:27017/mydb');

const OrderSchema = new mongoose.Schema({
  product: String,
  quantity: Number,
  price: Number,
  date: Date,
});

const Order = mongoose.model('Order', OrderSchema);

app.get('/sales-summary', async (req, res) => {
  try {
    // Aggregate total sales by product
    const summary = await Order.aggregate([
      {
        $group: {
          _id: '$product',
          totalSales: { $sum: { $multiply: ['$quantity', '$price'] } },
          count: { $sum: 1 }
        }
      }
    ]);
    res.json(summary);
  } catch (err) {
    res.status(500).send('Error aggregating sales');
  }
});

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

Project Explanation:

Implements basic pagination on database results using query parameters.


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

const app = express();

mongoose.connect('mongodb://localhost:27017/mydb');

const UserSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', UserSchema);

app.get('/users', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const skip = (page - 1) * limit;

  try {
    const users = await User.find().skip(skip).limit(limit);
    const total = await User.countDocuments();
    res.json({
      page,
      limit,
      totalPages: Math.ceil(total / limit),
      totalUsers: total,
      users,
    });
  } catch (err) {
    res.status(500).send('Error fetching users');
  }
});

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

Project Explanation:

Runs an Express server over HTTPS using self-signed SSL certificates.


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

const app = express();

// Load SSL cert and key files (generate with openssl for testing)
const sslOptions = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
};

app.get('/', (req, res) => {
  res.send('Secure HTTPS server with self-signed certificate!');
});

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

Project Explanation:

Combines IP whitelist and blacklist logic alongside rate limiting.


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

const app = express();

const whitelist = ['127.0.0.1'];
const blacklist = ['192.168.1.100'];

const limiter = rateLimit({
  windowMs: 60000,
  max: 10,
  skip: (req) => whitelist.includes(req.ip),
  handler: (req, res) => res.status(429).send('Too many requests'),
});

app.use((req, res, next) => {
  if (blacklist.includes(req.ip)) {
    return res.status(403).send('Access denied.');
  }
  next();
});

app.use(limiter);

app.get('/', (req, res) => {
  res.send('IP whitelist, blacklist and rate limit applied.');
});

app.listen(3000, () => {
  console.log('IP whitelist/blacklist + rate limit server running on port 3000');
});
      

Project Explanation:

Logs HTTP requests with Morgan and rotates log files daily.


// Import modules
const express = require('express');
const morgan = require('morgan');
const rfs = require('rotating-file-stream');
const path = require('path');

const app = express();

// Create a rotating write stream
const accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, 'log')
});

// Setup logger
app.use(morgan('combined', { stream: accessLogStream }));

app.get('/', (req, res) => {
  res.send('Morgan logging with rotating files!');
});

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

Project Explanation:

Validates request payloads using Joi before processing.


// Import modules
const express = require('express');
const Joi = require('joi');

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

// Define validation schema
const schema = Joi.object({
  name: Joi.string().min(3).required(),
  age: Joi.number().integer().min(0).required(),
});

app.post('/user', (req, res) => {
  const { error } = schema.validate(req.body);
  if (error) {
    return res.status(400).send(error.details[0].message);
  }
  res.send('User data is valid!');
});

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

Project Explanation:

Combines several security and performance middlewares in one Express app.


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

const app = express();

app.use(helmet());
app.use(cors());
app.use(compression());

const limiter = rateLimit({
  windowMs: 60000,
  max: 15,
  message: 'Too many requests',
});
app.use(limiter);

app.get('/', (req, res) => {
  res.send('Express app with Helmet, CORS, rate limit, and compression!');
});

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

Project Explanation:

Secures routes with JWT authentication and restricts access based on user roles.


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

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

const SECRET = 'supersecretkey';

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

// Login route - generates JWT
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);
  if (!user) return res.status(401).send('Invalid credentials');

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

// Middleware to verify JWT and role
function authRole(role) {
  return (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader) return res.status(401).send('Token missing');
    const token = authHeader.split(' ')[1];
    try {
      const payload = jwt.verify(token, SECRET);
      if (payload.role !== role) return res.status(403).send('Forbidden');
      req.user = payload;
      next();
    } catch {
      res.status(401).send('Invalid token');
    }
  };
}

app.get('/admin', authRole('admin'), (req, res) => {
  res.send('Welcome Admin!');
});

app.get('/user', authRole('user'), (req, res) => {
  res.send('Welcome User!');
});

app.listen(3000, () => {
  console.log('JWT with role-based access server running on port 3000');
});
      

Project Explanation:

Handles file uploads using Multer middleware, storing files on the server.


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

const app = express();

// Configure Multer storage
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Save uploads in 'uploads' folder
  },
  filename: (req, file, cb) => {
    // Use original file name with timestamp prefix to avoid conflicts
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage });

// Endpoint to upload single file named 'file'
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded');
  }
  res.send(`File uploaded successfully: ${req.file.filename}`);
});

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

Project Explanation:

Sets up real-time bidirectional communication with clients via socket.io.


// 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' event from client
  socket.on('chat message', (msg) => {
    // Broadcast message to all connected clients
    io.emit('chat message', msg);
  });

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

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

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

Project Explanation:

Implements custom rate limiting for each authenticated user.


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

const app = express();

const userLimits = new Map(); // Stores request counts per user ID
const WINDOW_TIME = 60000; // 1 minute
const MAX_REQUESTS = 5;

// Middleware to simulate authentication by user ID from headers
app.use((req, res, next) => {
  req.userId = req.headers['x-user-id'] || 'anonymous';
  next();
});

// Rate limiting middleware
app.use((req, res, next) => {
  const userId = req.userId;
  const now = Date.now();

  if (!userLimits.has(userId)) {
    userLimits.set(userId, { count: 1, startTime: now });
    return next();
  }

  const userData = userLimits.get(userId);

  if (now - userData.startTime > WINDOW_TIME) {
    // Reset count after window
    userLimits.set(userId, { count: 1, startTime: now });
    return next();
  }

  if (userData.count >= MAX_REQUESTS) {
    return res.status(429).send('Too many requests for this user');
  }

  userData.count++;
  userLimits.set(userId, userData);
  next();
});

app.get('/', (req, res) => {
  res.send(`Hello, user ${req.userId}. You have access.`);
});

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

Project Explanation:

Generates interactive API docs with Swagger UI and YAML/OpenAPI spec.


// Import modules
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json'); // Swagger spec file

const app = express();

// Serve Swagger UI at /api-docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.get('/hello', (req, res) => {
  res.send('Hello from Express with Swagger docs!');
});

app.listen(3000, () => {
  console.log('Swagger docs available at http://localhost:3000/api-docs');
});
      

Project Explanation:

Sends emails from Express backend via SMTP using Nodemailer.


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

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

// Configure SMTP transport
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your.email@gmail.com',
    pass: 'yourpassword',
  },
});

// Endpoint 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 sending email: ' + error.message);
    }
    res.send('Email sent: ' + info.response);
  });
});

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

Project Explanation:

Exports database data as CSV file downloadable from the API.


// Import modules
const express = require('express');
const { Parser } = require('json2csv');

const app = express();

const data = [
  { name: 'Alice', age: 30, email: 'alice@example.com' },
  { name: 'Bob', age: 25, email: 'bob@example.com' },
  { name: 'Carol', age: 35, email: 'carol@example.com' },
];

app.get('/export-csv', (req, res) => {
  const fields = ['name', 'age', 'email'];
  const parser = new Parser({ fields });
  const csv = parser.parse(data);

  res.header('Content-Type', 'text/csv');
  res.attachment('users.csv');
  res.send(csv);
});

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

Project Explanation:

Listens for and processes incoming webhooks (e.g., from payment gateways).


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

const app = express();
app.use(express.json()); // Parse JSON payloads

// Webhook endpoint
app.post('/webhook', (req, res) => {
  const event = req.body;
  console.log('Received webhook event:', event);

  // Process event here (e.g., validate, update DB)

  res.status(200).send('Webhook received');
});

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

Project Explanation:

Implements Server-Sent Events to push real-time data streams to clients.


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

const app = express();

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

  // Send a comment to keep connection alive every 15 seconds
  const keepAlive = setInterval(() => {
    res.write(': keep-alive\n\n');
  }, 15000);

  // Send data every 5 seconds
  let count = 0;
  const interval = setInterval(() => {
    count++;
    res.write(`data: Message number ${count}\n\n`);
    if (count === 10) {
      clearInterval(interval);
      clearInterval(keepAlive);
      res.end();
    }
  }, 5000);

  // Cleanup on client disconnect
  req.on('close', () => {
    clearInterval(interval);
    clearInterval(keepAlive);
  });
});

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

Project Explanation:

Sets HTTP Cache-Control headers to improve client-side caching.


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

const app = express();

app.get('/cached-data', (req, res) => {
  // Cache response for 60 seconds
  res.set('Cache-Control', 'public, max-age=60');
  res.json({ message: 'This response is cached for 60 seconds' });
});

app.listen(3000, () => {
  console.log('Cache-Control header server running on port 3000');
});
      

Project Explanation:

Dynamically resizes images on request using Sharp module.


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

const app = express();

app.get('/resize-image', async (req, res) => {
  const { width, height } = req.query;
  const inputPath = path.join(__dirname, 'images', 'input.jpg');

  if (!width || !height) {
    return res.status(400).send('Width and height query params required');
  }

  try {
    const resizedBuffer = await sharp(inputPath)
      .resize(parseInt(width), parseInt(height))
      .toBuffer();

    res.type('image/jpeg');
    res.send(resizedBuffer);
  } catch (error) {
    res.status(500).send('Error resizing image');
  }
});

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

Project Explanation:

Adds CSRF protection middleware to secure forms against cross-site request forgery attacks.


// Import modules
const express = require('express');
const cookieParser = require('cookie-parser');
const csrf = require('csurf');

const app = express();

app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));

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

app.get('/form', csrfProtection, (req, res) => {
  // Send form with CSRF token included
  res.send(`
    <form action="/process" method="POST">
      <input type="hidden" name="_csrf" value="${req.csrfToken()}" />
      <input type="text" name="data" />
      <button type="submit">Submit</button>
    </form>
  `);
});

app.post('/process', csrfProtection, (req, res) => {
  res.send('Form data processed successfully!');
});

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

Project Explanation:

Integrates OAuth2 login flow using Passport.js and Google strategy.


// Import modules
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const session = require('express-session');

const app = express();

app.use(session({ secret: 'secretKey', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

// Configure Passport Google OAuth strategy
passport.use(new GoogleStrategy({
  clientID: 'YOUR_GOOGLE_CLIENT_ID',
  clientSecret: 'YOUR_GOOGLE_SECRET',
  callbackURL: '/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
  // User profile info available here
  return done(null, profile);
}));

passport.serializeUser((user, done) => {
  done(null, user);
});
passport.deserializeUser((obj, done) => {
  done(null, obj);
});

// Routes
app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    res.send('Google OAuth login successful. User: ' + req.user.displayName);
  }
);

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

Project Explanation:

Adds real-time updates to GraphQL API using subscriptions with Apollo Server.


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

const app = express();
const pubsub = new PubSub();
const MESSAGE_ADDED = 'MESSAGE_ADDED';

// GraphQL schema
const typeDefs = gql`
  type Message {
    id: ID!
    content: String!
  }

  type Query {
    messages: [Message!]
  }

  type Mutation {
    addMessage(content: String!): Message
  }

  type Subscription {
    messageAdded: Message
  }
`;

let messages = [];
let idCount = 1;

// Resolvers
const resolvers = {
  Query: {
    messages: () => messages,
  },
  Mutation: {
    addMessage: (parent, { content }) => {
      const message = { id: idCount++, content };
      messages.push(message);
      pubsub.publish(MESSAGE_ADDED, { messageAdded: message });
      return message;
    },
  },
  Subscription: {
    messageAdded: {
      subscribe: () => pubsub.asyncIterator([MESSAGE_ADDED]),
    },
  },
};

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

  const http = require('http');
  const httpServer = http.createServer(app);
  server.installSubscriptionHandlers(httpServer);

  httpServer.listen(3000, () => {
    console.log('GraphQL subscription server running on port 3000');
  });
}

startServer();
      

Project Explanation:

Implements JWT access and refresh tokens for secure session management.


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

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

const ACCESS_TOKEN_SECRET = 'access-secret';
const REFRESH_TOKEN_SECRET = 'refresh-secret';

let refreshTokens = []; // Store refresh tokens

// Login route to issue tokens
app.post('/login', (req, res) => {
  const user = { id: 1, name: 'User' }; // Mock user

  const accessToken = jwt.sign(user, ACCESS_TOKEN_SECRET, { expiresIn: '15m' });
  const refreshToken = jwt.sign(user, REFRESH_TOKEN_SECRET);
  refreshTokens.push(refreshToken);

  res.json({ accessToken, refreshToken });
});

// Token refresh route
app.post('/token', (req, res) => {
  const { token } = req.body;
  if (!token || !refreshTokens.includes(token)) return res.sendStatus(403);

  jwt.verify(token, REFRESH_TOKEN_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    const accessToken = jwt.sign({ id: user.id, name: user.name }, ACCESS_TOKEN_SECRET, { expiresIn: '15m' });
    res.json({ accessToken });
  });
});

// Logout route to invalidate refresh token
app.post('/logout', (req, res) => {
  const { token } = req.body;
  refreshTokens = refreshTokens.filter(t => t !== token);
  res.send('Logged out');
});

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

Project Explanation:

Provides paginated data responses using query parameters for page and limit.


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

const app = express();

const data = [];
for (let i = 1; i <= 100; i++) {
  data.push({ id: i, name: `Item ${i}` });
}

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

  const start = (page - 1) * limit;
  const end = start + limit;

  const pagedData = data.slice(start, end);
  res.json({
    page,
    limit,
    totalItems: data.length,
    totalPages: Math.ceil(data.length / limit),
    data: pagedData,
  });
});

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

Project Explanation:

Adds secure HTTP headers using Helmet middleware for improved security.


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

const app = express();

app.use(helmet()); // Enable Helmet middleware

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

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

Project Explanation:

Custom middleware logs details about each incoming HTTP request.


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

const app = express();

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

app.get('/', (req, res) => {
  res.send('Logging middleware active');
});

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

Project Explanation:

Sends a file as a download to the client upon request.


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

const app = express();

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

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

Project Explanation:

Loads configuration values from .env file using dotenv module.


// Import modules
const express = require('express');
require('dotenv').config();

const app = express();

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

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

Project Explanation:

Implements multi-language support with i18next middleware.


// Import modules
const express = require('express');
const i18next = require('i18next');
const middleware = require('i18next-http-middleware');
const Backend = require('i18next-fs-backend');
const path = require('path');

const app = express();

// Initialize i18next with filesystem backend
i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en',
    backend: {
      loadPath: path.join(__dirname, '/locales/{{lng}}/translation.json'),
    },
  });

app.use(middleware.handle(i18next));

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

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