Skip to main content

Express

Step-by-step Express.js rate limiting tutorial with @unkey/ratelimit. Set per-route limits, return 429 responses, and skip the Redis dependency.
2 min read

What you'll build#

An Express server with rate-limited endpoints. Users who exceed the limit get a 429 response.

Time to complete: ~5 minutes

Prerequisites#

Create your Express app#

Add your root key#

Create a .env file:

.env
Warning
Never commit your .env file. Add it to .gitignore.

Create your server#

Create index.js:

index.js

Run your server#

Test it#

First 10 requests succeed. Requests 11+ get:

What's in the response?#

limiter.limit() returns:

FieldTypeDescription
successbooleantrue if allowed, false if rate limited
remainingnumberRequests left in current window
resetnumberUnix timestamp (ms) when window resets
limitnumberThe configured limit

Using as middleware#

For cleaner code, create reusable middleware:

middleware/ratelimit.js

createMiddleware helper#

Create an Express middleware from a Ratelimit instance:

Use on any route:

Different limits per route#

Create multiple limiters:

Next steps#

Troubleshooting#

Rate limit not applying?
  • Verify UNKEY_ROOT_KEY is set and has ratelimit.*.limit permission - Make sure you're using a consistent identifier per user - Check that .env is loaded before creating the limiter
TypeScript version?

Install types and use imports: