r/expressjs • • Mar 03 '26

After 2 years of Express.js in production, here are the middleware patterns that saved me and the ones I regret.

49 Upvotes

Running Express.js serving 15K users on a solo project. After 2 years of production firefighting, here's what actually worked vs what wasted my time:

Patterns that saved me:

1. Async error wrapper (eliminated 90% of unhandled rejections)

const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

Every route handler wrapped in this. No more try/catch blocks everywhere. Errors flow to the centralized error handler automatically.

2. Request correlation IDs

app.use((req, res, next) => {
  req.id = req.headers['x-request-id'] || crypto.randomUUID();
  next();
});

Attached to every log entry. When a user reports an issue, I search by their request ID and get the full picture in seconds.

3. Rate limiting per route, not globally Different endpoints have different limits. Login attempts: 5/min. API reads: 100/min. Webhooks: 500/min. Global rate limiting was either too strict for normal use or too loose for sensitive endpoints.

4. Graceful shutdown middleware On SIGTERM, stop accepting new connections, wait for in-flight requests to finish (with a 30s timeout), then close DB pools. Without this, every deploy caused dropped requests.

5. Response time header

app.use((req, res, next) => {
  const start = process.hrtime.bigint();
  res.on('finish', () => {
    const ms = Number(process.hrtime.bigint() - start) / 1e6;
    logger.info({ requestId: req.id, method: req.method, path: req.path, status: res.statusCode, ms });
  });
  next();
});

Every request logged with exact timing. Found 3 endpoints that were secretly taking 2s+ that I never would've caught otherwise.

Patterns I abandoned:

  • Complex validation middleware chains — Switched to Joi/Zod at the route level. Easier to read, easier to test.

  • Custom auth middleware per route — Moved to a single auth middleware with role-based config. Less code, fewer bugs.

  • Helmet with default config — Half the headers were breaking my frontend. Now I configure each header explicitly.

  • Morgan for logging — Replaced with pino. Morgan doesn't support structured JSON logging well, and structured logs are non-negotiable in production.

What Express patterns do you swear by? Anything you'd add to the "abandon" list?


r/expressjs • • Apr 04 '20

Question Version 5.0 and the roadmap of the Express.js

32 Upvotes

This PR has been with us for almost 6 years, which seems quite surprising.
https://github.com/expressjs/express/pull/2237

It does not seem to go anywhere right now. I was wondering if any of you have some idea of the roadmap of Express.js and when will we see the release of version 5.0.


r/expressjs • • Jul 22 '21

Tutorial Reddit clone built with express.js, mongodb and react

Thumbnail
youtube.com
19 Upvotes

r/expressjs • • Jun 08 '20

req.query and TypeScript ParsedQs

18 Upvotes

I just want to retrieve username as a String from [email protected]

In previous version of Express and Node, i just had a simple:

const username = req.query.username

It worked 'fine'.

Then I updated my app and now I have compile errors:

Type '(string & String) | (ParsedQs & String) | (string[] & String) | (ParsedQs[] & String)' is not assignable to type 'string'. ts(2322)

I tried googling, found this pull request which I don't really understand:

https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43427

Also, I found this older article that is almost understand, but the examples don't work for me (yet):

https://evanhahn.com/gotchas-with-express-query-parsing-and-how-to-avoid-them/

TL;DR how can I get url query parameters, be type safe and be sure there are no shenanigans going on, like arrays, nested object etc?

I want either a plain string, or error message from the api


r/expressjs • • Sep 29 '22

How to make your ExpressJS web server Invisible to attackers

15 Upvotes

Do you worry about your ExpressJS web server getting attacked by malicious actors?

There are ways to allow your trusted remote users access to your web server, while simultaneously making your web server invisible to bad actors.

Check out the following article concerning the OpenZiti SDK for NodeJS to learn more.

https://openziti.io/securing-nodejs-applications


r/expressjs • • Jul 20 '21

Tutorial How I structure my Node.js REST APIs

Thumbnail larswaechter.dev
15 Upvotes

r/expressjs • • Jul 04 '21

Question why do Express docs still use var instead of let or const?

15 Upvotes

Hello, I am relatively new to nodejs. Recently while Working my way through my express docs I realized that at every place express uses the old 'var' variables instead of let or const. As far as I know, node uses the latest version of v8 engine which has no compatibility issues with ES6, I would assume, since ES6 was released 5+ years ago, that express js being a nodejs framework would implement const and let. is there any specific reason why is it like this. Perhaps this in node culture?


r/expressjs • • Jul 10 '25

Express security best practices for software engineers

14 Upvotes

Hey all,

I'm Ahmad, founder of Corgea. We've built a scanner that can find vulnerabilities in express applications, so we decided to write a guide for software engineers on security best practices:

We have compiled a list of security best practices for Apps and APIs written in Express.

https://corgea.com/Learn/express-js-security-best-practices-2025

We wanted to cover Express security features, things we've seen developers do that they shouldn't, and all-around best practices. While we can't go into every detail, we've tried to cover a wide range of topics and gotcha's that are typically missed.

I'd love to get feedback from the community. Is there something else you'd include in the article? What's best practice that you've followed?

Thanks!


r/expressjs • • Nov 11 '20

Real time synced counter built using Socket.io, NodeJS and Express! The counter will be integrated in a live-quizzing platform I'm currently working on, to control the current question. GitHub repo and Demo in the comments. Please Star and Fork the repo if you like it! :)

14 Upvotes

r/expressjs • • Aug 31 '20

Full MERN stack Authentication

14 Upvotes

If you want to learn about MERN Stack authentication. This video can help you understand in learning it. This looks educative and informative.

https://www.youtube.com/channel/UCS3-MF_4ADqglU2OSly4vIw?sub_confirmation=1


r/expressjs • • Mar 07 '23

Basic Express.js + Typescript Boilerplate

13 Upvotes

Hey, I wanted to show you all my express.js + typescript boilerplate server. It should save me and a few other people time in the future to set up all the basics so you can get started right away. But first, I wanted to get some feedback on what could be improved.

Here are a few features I've included

- Package management with Yarn

- Testing with Jest and Supertest

- Cross-origin resource sharing enabled with cors

- Secured HTTP headers with helmet

- Logging with winston

- Environment variables with dotenv

- Compression with gzip

- Git hooks with husky and lint-staged

- Linting and enforced code style with eslint and prettier

- Containerization with Docker

Link to the Repo: https://github.com/Louis3797/express-ts-boilerplate


r/expressjs • • Oct 09 '21

REST API Boilerplate with JWT Authentication: Made with Express and MongoDB

13 Upvotes

r/expressjs • • Dec 28 '20

Created a CMS that supports Firestore, MySQL and SQLite

13 Upvotes

r/expressjs • • Jun 27 '19

Learn Expressjs from tutorials, courses & books

Thumbnail
reactdom.com
13 Upvotes

r/expressjs • • Jul 11 '21

Why is it encouraged to seperate your server or index.js and server.js instead of just keeping it in one file. I understand that there is a default script to start the server on one but why not just keep it in that one? I missing something here and don't know what I don't know.

12 Upvotes

Ex.

***server.js***

const express = require("express");

const server = express();

server.use(express.json());

server.get('/', (req, res) => {res.status(200).json({ serverMessage: 'Test endpoint' });});

module.exports = server;

***index.js***

const server = require('./api/server.js');

const PORT = 3000;server.listen(PORT, () => {console.log(`Server running on localhost:${PORT}`)})


r/expressjs • • Oct 03 '23

Tailwind Elements Stable v1.0.0. - a free, open-source UI Kit with 500+ components integrated with Express - is out.

Thumbnail
gallery
11 Upvotes

r/expressjs • • May 10 '23

Tutorial Express integration with Tailwind Elements - a free, open-source UI Kit

Thumbnail
gallery
11 Upvotes

r/expressjs • • Dec 25 '22

Books on Express.js Backend design

11 Upvotes

I am building a Backend for my application and it is my first "bigger" project.
However I feel like with every added line of code the chance of the Backend standing the test of time is getting slimmer and slimmer (there seem to be so many things to keep in mind while choosing design decisions).
Is there a Book that someone had actually read, that could help me?


r/expressjs • • May 13 '22

Why would I use express.urlencoded({extended: false{)?

11 Upvotes

I'm doing an Express tutorial and I can't figure out why we put the extended option in this method, and why we set it to false. I've spent two days searching for answers, reading docs. I understand that we need to parse the request object body for our server app because its been url-encoded by the browser. But everything I've read about that .urlencoded() method and the extended option still leaves me not knowing why we even use this option at all. Apparently if we set it to false, we use the querystring library which only parses simple strings and arrays. If we set it to true, it can parse just about anything. So ... why did the instructor say we had to put "extended: false" in there? Is it just to make our weenie little app faster because the querystring process is simpler than the qs process? If anybody knows the answer to this, I would be SUPER grateful.


r/expressjs • • Aug 08 '21

Question CORS Error

11 Upvotes

Hello, I have a problem with CORS. When I make a '/image' post request it throws an error witch says "Access to XMLHttpRequest at 'https://web-photographer.herokuapp.com/image' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.". For more context, front-end grabs images from the static images folder. Thanks in advance. This is my code:

app.use(cors({
  origin: ["https://gracious-lamarr-e2b03a.netlify.app","http://localhost:3000"],
  optionsSuccessStatus: 200,
  preflightContinue: false,
  contentlength: 100
}));
 
app.use(express.static('images'));

app.listen(PORT, () => { console.log(`Server is listening on port ${PORT}`) });

app.get('/', (req, res) => {
  res.send(`Everything is ok, and port is ${PORT}, new v`);
})

const clean = (oldHash) => {
  const directory = 'images';

  fs.readdir(directory, (err, files) => {
    if (err){
      return;
    }
    for (const file of files) {
      if(file === `${oldHash}.png`){
        fs.unlink(path.join(directory, file), err => {
          if (err){
            return;
          }
        });
      }
    }
  });
}


app.post('/image', jsonParser, (req, res) => {
  let { link } = req.body;
  const { oldHash, height, width } = req.body;

  const hash = crypto.createHash('md5').update(link).digest('hex');
  
  if(oldHash !== ""){
    clean(oldHash);
  }
  
  getImage(link, hash, height, width).then(() => {
    res.send(hash);
  });
});

app.post('/delete', jsonParser, (req, res) => {
  const { oldHash } = req.body;

  clean(oldHash);

  res.send("all good");
});

r/expressjs • • Jul 21 '20

Securing a REST API

11 Upvotes

Hello /expressjs!

I am currently learning Node.js (with Express) and one thing I have a hard time getting my head around is securing an API. There are a lot of tutorials out there focusing on a local setup. I've asked in a Slack and on SO and someone even recommended machine learning... I've even bought three Udemy courses as I thought they'll cover API security, but it always was mostly about setting user permissions or JWT tokens for POST/PUT/DELETE requests.

If I want to build an Airbnb-like app (not really but this should serve as an example because of the general functionality), how would I think about securing the API when having the following setup:
• Decoupled Backend and Frontend
• Backend / Express App on Heroku
• Frontend / Client Next.js App on Vercel
• A dedicated editor / admin area, where registered users can edit content (think adding a new room to Airbnb)
• But — the main application functionality / feature is visible and usable without signing up (again think Airbnb, every user can search for stays, rooms, cities, experiences, ...).
• Think of my routes like GET /, GET /api/events, PUT /api/events/new, GET /api/categories

I read a lot about all the security things like DDoS and so on, but what about "content scraping"? I once read about an app where their competition called their API and added the response to their own app. Is this really a thing? Or can I ignore this issue as my / route will be limited to return only so many items from the query (e.g. only show 20 results, add pagination to query for more)?
• When working with a headless CMS I have an access token so only I can access the CMS API
• Do I need to add another origin domain and only that is allowed to query data? (e.g. www.example.com vs. api.example.com) ?
• Or is it enough to add helmet?

Or more importantly — do I get totally wrong what "securing an API" really means?

Any help appreciated, thank you!


r/expressjs • • Nov 02 '19

A ready-to-use boilerplate for REST API Development with Node.js, Express, and MongoDB

11 Upvotes

Hello Everyone,

I have created a boilerplate application for API development built with Nodejs, ExpressJs, MongoDB.

Checkout: Nodejs Expressjs MongoDB Ready-to-use API Project Structure

Features:

  • Basic Authentication (Register/Login with hashed password)

  • Account confirmation with 4 (Changeable) digit OTP.

  • Email helper ready just import and use.

  • JWT Tokens, make requests with a token after login with Authorization
    header with value Bearer yourToken
    where yourToken
    will be returned in Login response.

  • Pre-defined response structures with proper status codes.

  • Included CORS.

  • Book example with CRUD operations.

  • Validations added.

  • Included API collection for Postman.

  • Light-weight project.

  • Test cases with Mocha and Chai.

  • Code coverage with Istanbuljs (nyc).

  • Included CI (Continuous Integration) with Travis CI.

  • Linting with Eslint.

Any feedback suggestions are much appreciated. Pull requests are welcome.

Have a nice day!


r/expressjs • • Nov 24 '22

I made a little tool for Express

10 Upvotes

Hey all,

I made a little tool for Express. I call it Holler. You can put it in your express routes to console log the request params/queries/body for you. It's easy to comment out later and saves you from having to clean up your console logs later.

I like it. I thought maybe other people would find it useful as well.

No worries, no hurries.

Tony

https://www.npmjs.com/package/@tonydiethelm/holler https://github.com/tonydiethelm/holler


r/expressjs • • Oct 01 '21

For some reason my APIs are working on the server side and when I am not making a separate routes folder but there is an error from the front end side as soon as I sort them into routes folder can someone please help me?

Thumbnail
gallery
10 Upvotes