Rate Limiter

Enabled Limit the amount of incoming requests to protect againts brute forcing.


Stores ip addresses of a requests in lru-cache and will throw an 429 Too Many Requests error when there will be too many requests. Based on https://unstorage.unjs.io/

โš ๏ธ Built-in rate limiter is not suitable for complex production applications. It is meant to help simpler applications handle the issue of brute forcing. To correctly protect your production application against brute forcing you should use solutions that work on the infrastructure layer, not the application layer. Check out tools such as https://www.cloudflare.com/en-gb/ddos/ & https://www.fail2ban.org/wiki/index.php/Main_Page.
โ„น Read more about taking precautions against brute forcing here.

Usage

This middleware is enabled globally by default. You can customize it both globally and per route like following:

nuxt.config.ts
export default defineNuxtConfig({  // Global  security: {    rateLimiter: {      // options    }  }  // Per Route  routeRules: {    '/my-secret-route': {      security: {        rateLimiter: {          // options        }      }    }  }})

You can also disable the middleware globally or per route by setting rateLimiter: false.

Options

Rate limiter accepts following configuration options:

type RateLimiter = {  tokensPerInterval: number;  interval: number;  headers: boolean;  throwError: boolean;  driver: {    name: string;    options: Record<string, any>;  };};

tokensPerInterval

  • Default: 150

The amount of requests that reach the application before rate limiting will block further connection. Based on Twitter search rate limiting.

interval

  • Default: 300000

The time value in miliseconds after which the rate limiting will be reset. For example, if you set it to 10000 and tokensPerInterval: 3 it will allow three requests from one IP address in 10 seconds and the next one in this interval will be banned. After 10 seconds however, user will be able to send requests again.

headers

  • Default: false

When set to true it will set the response headers: X-Ratelimit-Remaining, X-Ratelimit-Reset, X-Ratelimit-Limit with appriopriate values.

throwError

  • Default: true

Whether to throw Nuxt Error with appriopriate error code and message. If set to false, it will just return the object with the error that you can handle.

driver

  • Default: { name: 'lruCache' }

Storage used to store the rate limited IP addresses. By default uses LRU Cache but you can change it to any of the drivers supported by unstorage.

โš ๏ธ Remember to use the camelCase name of the driver, i.e. lruCache not lru-cache.

To use for example Vercel KV store we would use following configuration:

rateLimiter: {  driver: {    name: 'vercelKv',    options: {      // url: "https://<your-project-slug>.kv.vercel-storage.com",      // Other options    }  }}