Web Development · Module 10 · Lesson 31 min read

Middleware & Environment Variables

Middleware

A function that runs between the request arriving and your route handler. It can read or change req and res, end the request, or call next() to continue.

JavaScript
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();
});

Common middleware

MiddlewarePurpose
express.json()parse JSON bodies
cors()allow your front end's domain to call the API
helmet()set secure HTTP headers
express-rate-limitstop abuse and brute-force attempts
your own requireAuthcheck the login token before protected routes

Error-handling middleware

Has four parameters and goes last:

JavaScript
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
});

Environment variables

Keep secrets and settings out of your code:

ini
# .env  (add to .gitignore!)
PORT=3000
DATABASE_URL=postgres://...
JWT_SECRET=a-long-random-string

Load them with node --env-file=.env index.js (Node 20+) or the dotenv package, then read process.env.JWT_SECRET. On hosting platforms, set them in the dashboard.

Example

JavaScript
import express from "express";
import cors from "cors";

const app = express();
app.use(express.json());
app.use(cors({ origin: process.env.FRONTEND_URL ?? "http://localhost:5173" }));

// Logger middleware
app.use((req, res, next) => {
  const start = Date.now();
  res.on("finish", () =>
    console.log(`${req.method} ${req.url} ${res.statusCode} ${Date.now() - start}ms`));
  next();
});

// Simple auth middleware (demo: checks an API key header)
function requireApiKey(req, res, next) {
  if (req.get("x-api-key") !== process.env.API_KEY) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  next();
}

app.get("/api/public", (req, res) => res.json({ ok: true }));
app.get("/api/secret", requireApiKey, (req, res) => res.json({ secret: 42 }));

// Error handler — always last
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
});

app.listen(process.env.PORT ?? 3000);
// 💻 npm install express cors → node --env-file=.env index.js