Task 1: Basic Server Setup

Create a new Express server with:

  • CORS middleware enabled
  • express.json() middleware
  • A simple logging middleware that shows timestamp, method, and URL
  • At least 3 GET routes that return different data
  • 404 handler
  • Error handling middleware

Task 2: Authentication Middleware

Create your own authentication middleware function that:

  • Checks for an Authorization header in incoming requests
  • Validates that the token is Bearer letmein
  • Returns appropriate error responses for missing or invalid tokens
  • Allows valid requests to continue to the route handler

Create these routes:

  • GET / → returns { message: "Public page" } (no auth)
  • GET /protected → uses checkAuth, returns { message: "Protected page" }
  • GET /admin → also uses checkAuth, returns { message: "Admin dashboard" }

Test cases:

  • / → works without headers
  • /protected or /admin:
    • No header → 401
    • Wrong token → 403
    • Token Bearer letmein → works

Task 3: Request Counter Middleware

Create a middleware that counts how many requests have been made to your server. Your middleware should:

  1. Keep track of the total number of requests (start at 0)
  2. Increment the counter for each request
  3. Add a header to the response called X-Request-Count with the current count
  4. Log the count with each request: Request #5 - GET /users
  5. Also return the counter value in the JSON response body.

Hint: Declare your counter variable (like let count = 0) outside the middleware function so it persists across requests.

Apply this middleware to all routes and test with multiple requests to see the counter increase.

Tags: