Course contentsShow
← Node.js
Lesson 552 of 1,9806. Networking and HTTP FundamentalsFree lesson

Authentication Interceptors

Create reusable logic that inspects authorization headers before reaching the primary business handler.

In this lesson, you will learn how to create reusable logic that inspects authorization headers before a request ever reaches your primary business handler.

The Concept of Interception

In professional Node.js applications, you don't want to rewrite the same "check if the user is logged in" code inside every single route. Instead, you use an Authentication Interceptor (often called Middleware). Think of this as a security checkpoint: it sits between the incoming raw HTTP request and your final route handler. It has the authority to either allow the request to proceed or stop it dead in its tracks.

Implementing the Interceptor

The interceptor inspects the Authorization header. If the header is missing or invalid, it sends a 401 Unauthorized response immediately, preventing your sensitive business logic from ever executing.

const authInterceptor = (req, res, next) => {
  const authHeader = req.headers['authorization'];

  // Check if the token exists and follows our expected format
  if (!authHeader || authHeader !== 'Bearer my-secret-token') {
    res.statusCode = 401;
    res.end('Access Denied: Invalid Credentials');
    return; // Stop execution here
  }

  // If valid, move to the next function in the chain
  next();
};

// Usage in a routing system
app.use('/api/private-data', authInterceptor);
app.get('/api/private-data', (req, res) => {
  res.end('Welcome to the vault!');
});

Why Use Interceptors?

By decoupling authentication from your route handlers, you gain two major benefits:

  1. DRY (Don't Repeat Yourself): You write the authentication logic once and apply it to as many routes as needed.
  2. Safety: You reduce the risk of human error where a developer might forget to check for a token in a new, protected endpoint. If the interceptor is applied to the route's path prefix, the security is enforced automatically.

If the interceptor succeeds, it calls the next() function, passing control to your business logic. If it fails, it terminates the request cycle early, keeping your application secure and your codebase clean.

Key Takeaway: Authentication interceptors provide a centralized, reusable layer to validate credentials before requests reach your core application logic.