JAVASCRIPT

Secure Express API Endpoints with Custom API Key Middleware

Implement a custom middleware in Node.js with Express to protect your API endpoints by validating an API key sent in the request header, ensuring authorized access.

const express = require('express');
const dotenv = require('dotenv'); // Install with `npm install dotenv`

dotenv.config(); // Load environment variables from .env file

const app = express();
const PORT = process.env.PORT || 3000;

// Retrieve the secret API key from environment variables
const VALID_API_KEY = process.env.API_KEY_SECRET;

if (!VALID_API_KEY) {
  console.error('Error: API_KEY_SECRET environment variable is not set. Please set it in your .env file.');
  process.exit(1);
}

// Custom API Key Authentication Middleware
const authenticateApiKey = (req, res, next) => {
  const apiKey = req.headers['x-api-key']; // Expecting the API key in a custom header

  if (!apiKey) {
    return res.status(401).json({ error: 'Unauthorized: No API Key provided' });
  }

  if (apiKey === VALID_API_KEY) {
    next(); // API Key is valid, proceed to the next middleware/route handler
  } else {
    return res.status(403).json({ error: 'Forbidden: Invalid API Key' });
  }
};

// Apply the authentication middleware to specific routes or globally
// Example 1: Apply to a single route
app.get('/api/data', authenticateApiKey, (req, res) => {
  res.json({ message: 'This is sensitive data, access granted with valid API key.' });
});

// Example 2: Apply to a group of routes (e.g., all routes under /api/admin)
const adminRouter = express.Router();
adminRouter.use(authenticateApiKey); // Apply middleware to all routes in this router

adminRouter.get('/users', (req, res) => {
  res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});

adminRouter.post('/settings', (req, res) => {
    res.json({ status: 'Settings updated' });
});

app.use('/api/admin', adminRouter);


// Public route (no API key required)
app.get('/', (req, res) => {
  res.send('Welcome to the public API endpoint!');
});


app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Public endpoint: http://localhost:${PORT}/`);
  console.log(`Protected endpoint (requires 'x-api-key' header): http://localhost:${PORT}/api/data`);
  console.log(`Protected admin endpoint: http://localhost:${PORT}/api/admin/users`);
  console.log(`Use API_KEY_SECRET from your .env file as 'x-api-key' header.`);
});
How it works: This Node.js and Express snippet demonstrates how to secure API endpoints using a custom middleware for API key authentication. It reads a `VALID_API_KEY` from environment variables for security. The `authenticateApiKey` middleware checks for an `x-api-key` header in incoming requests. If the key is missing or invalid, it returns a 401 or 403 error, respectively. Otherwise, it calls `next()` to pass control to the route handler. This allows developers to protect specific API routes or groups of routes, ensuring only authorized clients can access them.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs