Express 5 cheatsheet
Express 5: Middleware
6 common Express 5 tasks.
Write middleware
Run code on every request, then call next() to continue.
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
Enable CORS
Allow browsers on other origins to call your API.
npm install cors
import cors from "cors";
app.use(cors({ origin: "https://app.example.com" }));
Set security headers
Add common protective HTTP headers.
npm install helmet
import helmet from "helmet";
app.use(helmet());
Log requests
Log each request with the morgan middleware.
npm install morgan
import morgan from "morgan";
app.use(morgan("combined"));
Trust a reverse proxy
Read the client's real IP and protocol behind a proxy such as Nginx.
app.set("trust proxy", 1);