We’ll create a simple custom authentication middleware function called checkAuth that:

  1. Checks if the request has an authorization header
  2. If no header, return status 401 with message "Missing authorization header"
  3. If header exists but is not "Bearer secret123", return status 403 with message "Access denied"
  4. If header is correct, call next() to continue

Here’s the implementation:

function checkAuth(req, res, next) {
  const authHeader = req.headers.authorization;

  // Check if Authorization header exists
  if (!authHeader) {
    return res.status(401).json({ error: "Missing authorization header" });
  }

  // Check if the token is correct
  if (authHeader !== "Bearer secret123") {
    return res.status(403).json({ error: "Access denied" });
  }

  // Token is correct, continue to next middleware or route handler
  next();
}

Now create these routes:

// Public route - no auth needed
app.get("/public", (req, res) => {
  res.json({ message: "Public page" });
});

// Protected route - uses checkAuth middleware
app.get("/protected", checkAuth, (req, res) => {
  res.json({ message: "Protected page" });
});

Important: Only apply the checkAuth middleware to the /protected route, not to all routes.

Test with Postman or JavaScript:

You can test these routes using Postman or frontend JavaScript code:

Postman:

  • GET /public (should work without auth)
  • GET /protected (should fail with 401)
  • GET /protected with header Authorization: Bearer wrong (should fail with 403)
  • GET /protected with header Authorization: Bearer secret123 (should work)

Frontend JavaScript example:

// Test protected route with wrong token (should fail with 403)
fetch("http://localhost:3000/protected", {
  headers: {
    Authorization: "Bearer wrong",
  },
});

// Test protected route with correct token (should work)
fetch("http://localhost:3000/protected", {
  headers: {
    Authorization: "Bearer secret123",
  },
});


Repo link

Tags: