Express server for an Angular application part 6: limit connections and prevent DDoS

Marco Zuccaroli
ITNEXT
Published in
2 min readJun 5, 2019

--

Express.js is a web application framework for Node.js designed for building web applications, in this series of articles I will explain step by step how i realized an express server with some advanced functions that i use for my single page application made with Angular 7.

I will discuss the 7 main problem that i solved in different articles:

  1. getting started
  2. serve files from a bucket
  3. redirect some calls to an external service
  4. redirect http to https requests
  5. redirect non-www to www requests
  6. limit connections and prevent DDoS
  7. handle some cache

In this article I will discuss how to limit connections made by a single ip in a short amount of time.

Reference repository

A working example of this project is available at:

https://github.com/mzuccaroli/express_server_for_angular_example the master branch contain the final full project but there’s a dedicated branch for every single article, for this one the reference https://github.com/mzuccaroli/express_server_for_angular_example/tree/feature/limiter

About environments

For this feature like the ones developed before I chose to introduce different behaviors for develop and production, like in the previous part of this tutorial “how to redirect http request to https” I use an “_environment” variable to separate local development behaviors from production ones. For more info see the article

Why limit connections

Put a limit on the number of connections made by a single ip address in a short amount of time is definitely a good idea. It prevents malfunctionings, unnecessary overloads on the server and provide protection from DDos attacks.
Express provide a very easy to use library that will easily get the job done.

How to limit connections

Let’s start with installing express-rate-limit and add it to our package.json

$ npm install — save express-rate-limit

Now you can add to your code the following part right the “app” declaration:

that’s all you need to enable limits, you can tweak the limiter settings by edit the “windowMs” value for change the amount of time and “max” to set the connections limit.
It’s a very simple modification to your server but provide a great improvement, there is really no reason to not do it.

The next, and last, step of our path to create a good express server will be adding some cache functions to improve the speed of our application and will be discussed in the next article.

--

--