Skip to content

Instantly share code, notes, and snippets.

@roybarber
Last active October 3, 2024 09:11
Show Gist options
  • Save roybarber/784f4da5fb402fc6803e26701d6a7f03 to your computer and use it in GitHub Desktop.
Save roybarber/784f4da5fb402fc6803e26701d6a7f03 to your computer and use it in GitHub Desktop.
Next.js + Vercel Firewall - Rate Limit
import { unstable_checkRateLimit as checkRateLimit } from '@vercel/firewall'
import { DEFAULT_SERVER_ERROR_MESSAGE, createSafeActionClient,} from 'next-safe-action'
import { headers } from 'next/headers'
// Creating an action client using the createSafeActionClient function
export const actionClient = createSafeActionClient({
// Handling returned server errors
handleReturnedServerError(e) {
// If the error is an instance of Error, return its message
if (e instanceof Error) {
return e.message
}
// Otherwise, return the default server error message
return DEFAULT_SERVER_ERROR_MESSAGE
},
}).use(async ({ next }) => {
// Checking the rate limit using the checkRateLimit function
const { rateLimited, error } = await checkRateLimit('my-rate-limit-id', {
// Passing the headers to the checkRateLimit function
headers: headers(),
})
// If the rate limit is exceeded, throw an error
if (rateLimited) {
throw new Error('Too many requests')
}
// Proceed to the next middleware or handler with the rate limit error in the context
return next({
ctx: {
ratelimit: {
error,
},
},
})
})
@roybarber
Copy link
Author

Create the rule in Vercel Firewall & copy the rate limit ID you get, then you can use it to checkRateLimit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment