0
0
Expressframework~5 mins

Protecting routes with auth middleware in Express

Choose your learning style9 modes available
Introduction

Protecting routes with auth middleware helps keep parts of your app safe. It checks if a user is allowed before they see certain pages.

When you want only logged-in users to access their profile page.
When you need to hide admin pages from regular users.
When you want to check if a user has permission before showing sensitive data.
When you want to stop visitors from accessing private routes without signing in.
Syntax
Express
function authMiddleware(req, res, next) {
  if (req.user) {
    next(); // allow access
  } else {
    res.status(401).send('Not authorized');
  }
}

app.get('/protected-route', authMiddleware, (req, res) => {
  res.send('This is protected');
});

The middleware function runs before the route handler.

Call next() to continue if the user is allowed.

Examples
Checks if req.user exists to allow access.
Express
function authMiddleware(req, res, next) {
  if (req.user) {
    next();
  } else {
    res.status(401).send('Please log in');
  }
}
Protects the dashboard route so only authorized users can see it.
Express
app.get('/dashboard', authMiddleware, (req, res) => {
  res.send('Welcome to your dashboard');
});
Protects all routes under /admin with the auth middleware.
Express
app.use('/admin', authMiddleware);

app.get('/admin/settings', (req, res) => {
  res.send('Admin settings page');
});
Sample Program

This example shows a simple Express app with a public route and a protected route. The authMiddleware checks if the request has a header x-user. If yes, it allows access to the profile page. Otherwise, it sends a 401 error.

Express
import express from 'express';
const app = express();

// Simple auth middleware
function authMiddleware(req, res, next) {
  // Simulate user logged in if header 'x-user' exists
  if (req.headers['x-user']) {
    next();
  } else {
    res.status(401).send('Not authorized');
  }
}

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

// Protected route
app.get('/profile', authMiddleware, (req, res) => {
  res.send('This is your profile');
});

// Start server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Middleware runs in the order you add it, so place auth middleware before protected routes.

In real apps, auth checks usually look at tokens or sessions, not just headers.

Always send a clear message or redirect when access is denied.

Summary

Auth middleware checks if a user can access a route.

Use next() to allow access, or send an error to block.

Protect routes by adding middleware before route handlers.