Last active
January 6, 2020 14:33
-
-
Save arash16/f6e45eb6df849eb3a8252c7a6684abd3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simplified Sample Code for limiting nuxt ssr per user | |
const { RateLimiterMemory } = require("rate-limiter-flexible"); | |
const { cpuFree } = require('os-utils'); | |
// each user has 1SSR per minute | |
const ipRateLimiter = new RateLimiterMemory({ | |
points: 1, // 1 SSR | |
duration: 60, // Per minute | |
}); | |
let warmup = true; | |
setTimeout(() => warmup = false, 60 * 1000); // 1-minute cooldown | |
let freeCpu = 1; | |
cpuFree(function h(val) { | |
freeCpu = val; | |
cpuFree(h); | |
}); | |
// middleware used on express, before nuxt.render is called | |
module.exports = async function (req, res, next) { | |
// in the first minute of starting server, SSR is disabled | |
if (warmup || freeCpu < 0.2) res.spa = true; | |
if (!res.spa) { | |
const ip = req.headers['cf-connecting-ip'] || req.header('x-forwarded-for') || req.connection.remoteAddress; | |
ipRateLimiter.consume(ip, 1) | |
.catch(() => res.spa = true) | |
.finally(next); | |
return; | |
} | |
next(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment