Security

This is too often overlooked or completely ignored. But just a few lines of code can make your app much harder to break.

  • Helmet helps you secure your Express apps by setting various HTTP headers.

  • Add an API rate limit to reduce the number of actions and protect from DDoS and brute force attacks.

  • Enforce HTTPS

Helmet

$ yarn add helmet

Start protecting your app with helmet

import helmet from "helmet";

export const createApp = () => {
  // ...
  app.use(helmet());
  app.use(helmet.noCache()); // disable browser caching
  app.use(
    helmet.hsts({
      includeSubDomains: true, // enforce https everywhere
      preload: true
    })
  ); 
 // ...
};

API Rate Limit

The library node-rate-limiter-flexible helps us keep track of requests count.

We are going to create a new folder middlewaresand add RateLimiter.ts to it.

We can now use this middleware in app.ts.

The number of requests is now limited to 10 per seconds. Go ahead an experiment with higher numbers to see if you will get rejected.

Or instead, we can also write a test for this:

security branch available on GitHub.

Last updated

Was this helpful?