How to use express-rate-limit - 10 common examples

To help you get started, we’ve selected a few express-rate-limit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github autoai-org / AID / components / discovery / src / main.ts View on Github external
async function bootstrap() {
  if (config.MONGO_URI==="") {
    console.error("[db]: connection string is undefined!")
  } else {
    console.info("[db]:connecting to " + config.MONGO_URI)
    const app = await NestFactory.create(AppModule);
    await setupAdminPanel(app);
    app.use(helmet());
    app.use(
      rateLimit({
        windowMs: 60 * 1000, // 15 minutes
        max: 100, // limit each IP to 100 requests per windowMs
      }),
    );
    app.setBaseViewsDir(join(__dirname, '..', 'src', 'views'));
    app.setViewEngine('hbs');
    const options = new DocumentBuilder()
      .setTitle('AID Discovery')
      .setDescription('The AID Discovery API')
      .setVersion('0.0.1')
      .addTag('Model')
      .addTag('User')
      .addTag('Extension')
      .build();
    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup('api', app, document);
github sentinel-official / sentinel / master-node-nodejs / src / index.js View on Github external
/**
 * Server setup
 */
import express from 'express';
import chalk from 'chalk';
import RateLimit from 'express-rate-limit';

import middlewaresConfig from './config/middlewares';
import constants from './config/constants';
import ApiRoutes from './routes';

import { dbo } from './db/database'

dbo()

let limiter = new RateLimit({
  windowMs: 60 * 60 * 1000, // 60 minutes
  max: 2000000, // limit each IP to 100 requests per windowMs
  delayMs: 0, // disable delaying - full speed until the max limit is reached
  message: "Too many requests maid from this IP, please try again after an hour"
});

const app = express();

// Wrap all the middlewares with the server
middlewaresConfig(app);

app.enable('trust proxy');
app.use(limiter);

// Add the apiRoutes stack to the server
if (process.env.NODE_ENV !== 'test') app.use(ApiRoutes);
github Autodesk-Forge / forge-rcdb.nodejs / src / server / index.js View on Github external
store: new MongoStore({
      url: dbConfig.connectionString?dbConfig.connectionString:util.format('mongodb://%s:%s@%s:%d/%s',
        dbConfig.user,
        dbConfig.pass,
        dbConfig.dbhost,
        dbConfig.port,
        dbConfig.dbName),
      autoRemove: 'native',  // Default
      autoRemoveInterval: 10 // In minutes. Default
    })
  }))

  app.use(helmet())

  const limiter = new RateLimit({
    windowMs: 1 * 60 * 1000, // 1 minute
    delayMs: 0, // disabled
    max: 1000
  })

  app.use('/api/', limiter)
}

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.set('trust proxy', 1)
app.use(cookieParser())

///////////////////////////////////////////////////////////
// Services setup
//
github jkchao / blog-service / src / main.ts View on Github external
app.useGlobalPipes(
    new ValidationPipe({
      transform: true
    })
  );

  // app.useGlobalGuards(new AuthIsVerifiedGuard());

  // 支持 CORS
  app.enableCors({
    credentials: true
  });
  app.use(helmet());
  app.use(bodyParser());
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: 100
    })
  );
  app.use(compression());

  await app.listen(config.APP_PORT, '0.0.0.0', () => {
    logger.log(config.APP_NAME + ' start: 0.0.0.0:' + config.APP_PORT);
  });
}
github mozilla / mozillafestival.org / server.js View on Github external
import GoogleSpreadsheet from "google-spreadsheet";
// import proposalHandler from "./lib/proposal-handler";

import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router';
import Main from './main.jsx';

Habitat.load();

var app = express(),
  env = new Habitat();

app.enable('trust proxy');

var limiter = RateLimit({
  windowMs: 60 * 1000,
  delayMs: 1000,
  max: 5,
  global: false
});

app.use(compression());
app.use(express.static(path.resolve(__dirname, `public`), {
  maxAge: '1m' // expire cache in 1 month
}));
app.use(bodyParser.json());


/*
app.post(`/add-proposal`, limiter, (req, res) => {
  // line breaks are essential for the private key.
github te-emprego / api / src / middlewares / RateLimit.middleware.ts View on Github external
import RateLimit from 'express-rate-limit'
import config from '@config'

const limiter = new RateLimit({
  windowMs: config.requests.window,
  max: config.requests.limit
})

export const loginLimiter = new RateLimit({
  windowMs: 2 * 60 * 1000,
  max: 10
})

export default limiter
github GetStream / Winds / api / src / server.js View on Github external
import { startSampling } from './utils/watchdog';
import { setupExpressRequestHandler, setupExpressErrorHandler } from './utils/errors';
import User from './models/user';

const api = express();

setupExpressRequestHandler(api);

api.use(cors({ maxAge: 1728000 }));
api.use(compression());
api.use(bodyParser.urlencoded({ extended: true }));
api.use(bodyParser.json({ limit: '5mb' }));

api.enable('trust proxy');
api.use(
	new limit({
		windowMs: 60 * 1000,
		max: 1000,
		delayMs: 0,
	}),
);

api.set('json spaces', 4);

api.use(
	jwt({ secret: config.jwt.secret }).unless({
		path: [
			'/',
			'/health',
			/\/bull*/,
			'/email/weekly',
			'/status',
github staart / api / src / helpers / middleware.ts View on Github external
RATE_LIMIT_TIME,
  SPEED_LIMIT_DELAY,
  SPEED_LIMIT_COUNT,
  SPEED_LIMIT_TIME,
  PUBLIC_RATE_LIMIT_TIME,
  PUBLIC_RATE_LIMIT_MAX
} from "../config";
import { ApiKey } from "../interfaces/tables/organization";
import { joiValidate, includesDomainInCommaList } from "./utils";
import { trackUrl } from "./tracking";
const store = new Brute.MemoryStore();
const bruteForce = new Brute(store, {
  freeRetries: BRUTE_FREE_RETRIES,
  lifetime: BRUTE_LIFETIME
});
const rateLimiter = RateLimit({
  windowMs: RATE_LIMIT_TIME,
  max: RATE_LIMIT_MAX
});
const publicRateLimiter = RateLimit({
  windowMs: PUBLIC_RATE_LIMIT_TIME,
  max: PUBLIC_RATE_LIMIT_MAX
});
const speedLimiter = slowDown({
  windowMs: SPEED_LIMIT_TIME,
  delayAfter: SPEED_LIMIT_COUNT,
  delayMs: SPEED_LIMIT_DELAY
});

/**
 * Handle any errors for Express
 */
github staart / api / src / helpers / middleware.ts View on Github external
PUBLIC_RATE_LIMIT_TIME,
  PUBLIC_RATE_LIMIT_MAX
} from "../config";
import { ApiKey } from "../interfaces/tables/organization";
import { joiValidate, includesDomainInCommaList } from "./utils";
import { trackUrl } from "./tracking";
const store = new Brute.MemoryStore();
const bruteForce = new Brute(store, {
  freeRetries: BRUTE_FREE_RETRIES,
  lifetime: BRUTE_LIFETIME
});
const rateLimiter = RateLimit({
  windowMs: RATE_LIMIT_TIME,
  max: RATE_LIMIT_MAX
});
const publicRateLimiter = RateLimit({
  windowMs: PUBLIC_RATE_LIMIT_TIME,
  max: PUBLIC_RATE_LIMIT_MAX
});
const speedLimiter = slowDown({
  windowMs: SPEED_LIMIT_TIME,
  delayAfter: SPEED_LIMIT_COUNT,
  delayMs: SPEED_LIMIT_DELAY
});

/**
 * Handle any errors for Express
 */
export const errorHandler = (
  error: any,
  req: Request,
  res: Response,
github bs32g1038 / node-blog / server / middlewares / rate-limit.middleware.ts View on Github external
use(req: Request, res: Response, next: NextFunction) {
        if (req.originalUrl.includes('/api/comments') && req.method === 'POST' && !auth(req)) {
            return rateLimit({ windowMs: 12 * 60 * 1000, max: 100 })(req, res, next);
        } else if (req.originalUrl.includes('/api')) {
            return rateLimit({ windowMs: 3 * 60 * 1000, max: 1000 })(req, res, next);
        }
        next();
    }
}

express-rate-limit

Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.

MIT
Latest version published 2 months ago

Package Health Score

89 / 100
Full package analysis

Popular express-rate-limit functions