Search code examples
javascriptnode.jsnext.jsvercelnext.js13

how to rate limit next.js server actions?


I am using server actions in next.js as per the documentation on Server Actions

Everything is working well, but now I am looking to rate limit the server action, in order to prevent spam or attacks. I know how to rate limit nextjs requests, as this is laid out well in the documentation as well in a rate limiting guide.

But I so far didn't figure out how to rate limit a specific server action, as the server action posts to the root of the document, and rate limiting can only be specified by root path. Does someone have an elegant solution for this? I know I can create an api route and rate limit it, but I like the way to do things with server actions and would like to stick to this if possible.

Thanks a lot!


Solution

  • you can still use the same approach mentioned on the docs. Because server actions will issue a POST request to the same route you're calling it from.

    For example, if I call a server action while at a route of "/blogs/posts", the following middleware will run:

    import type { NextRequest } from 'next/server';
     
    export function middleware(request: NextRequest) {
      if (request.method === 'POST') {
        // apply your logic here
        console.log(request);
      }
    }
     
    export const config = {
      matcher: '/blogs/posts',
    };