Created
August 22, 2022 19:55
-
-
Save enesakar/156bc542e26615a74169f1f3334d8f94 to your computer and use it in GitHub Desktop.
This file contains 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
import { Redis } from "@upstash/redis/cloudflare"; | |
import { MultiRegionRatelimit } from "@upstash/ratelimit"; | |
export interface Env { | |
} | |
const cache = new Map(); | |
export default { | |
async fetch( | |
request: Request, | |
env: Env, | |
_ctx: ExecutionContext, | |
): Promise<Response> { | |
if (new URL(request.url).pathname == "/favicon.ico") { | |
return new Response(null, { status: 400 }); | |
} | |
const ratelimit = new MultiRegionRatelimit({ | |
redis: [ | |
new Redis({ | |
url: "https://us1-merry-macaque.upstash.io", | |
token: "AX_sASQgODM5ZjExZGEtI4ZmVjNmE3ZDk3NDIxMmEwNmNkYjVmOGVmZTk5MzQ=", | |
}), | |
new Redis({ | |
url: "https://eu2-neat-caribou.upstash.io", | |
token: "AXe5ASQgNmM5YmFFiMWExMDc5NmU2NGFiYWEwMzk2ZjE4ZWQ3N2Y4YTE=", | |
}) | |
], | |
limiter: MultiRegionRatelimit.fixedWindow(5, "5 s"), | |
ephermeralCache: cache, | |
}); | |
const userIP: string = request.headers.get('CF-Connecting-IP') || "none"; | |
const data = await ratelimit.limit(userIP); | |
if (data.success) { | |
// if you use CF Workers to intercept another site, uncomment below | |
// return await fetch(request); | |
return new Response(JSON.stringify({ message: "Success, you are not rate limited.", ip: userIP, data }, null, 2), { status: 200 }); | |
} else { | |
// show an error page for rate limited users | |
return new Response(JSON.stringify({ message: "You are rate limited, try again later.", ip: userIP, data }, null, 2), { status: 200 }); | |
} | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment