deadcoder0904
deadcoder0904

Reputation: 8683

How to call React Server Actions (in Next.js 14) programmatically to simulate rate limits?

I have a signup action that takes an email as a form input using FormData & adds a value to database.

I want to simulate rate limit using just fetch api. How can I do that?

I don't want to use playwright or simulate 100s of requests in browser by having another button.

I just want to use fetch. Is it technically possible?

I tried with the following code:

async function main() {
  const formData = new FormData()
  formData.append('email', '[email protected]')

  const res = await fetch('http://localhost:3000/signup', {
    method: 'POST',
    body: formData,
  })

  const data = await res.json()

  console.log({ data })
}

main()

And typed tsx ./rate-limit/signup.ts in the terminal.

But it only gave me the html back.

Curious if its possible at all like /api routes?

Upvotes: 1

Views: 951

Answers (1)

stonith404
stonith404

Reputation: 530

You have to provide the Next-Action header:

 const res = await fetch('http://localhost:3000/signup', {
    method: 'POST',
    body: formData,
    headers: {
        'Next-Action': '0917c6804f07eaf34c42aa6867f90bf00983db90' // <-- Replace with your action id
    }
  })

I didn't find out how to get this action id automatically but manually you can obtain it by inspecting the request headers in the network tab of the browser dev tools.

Edit: You can find Next-Action number by using a library like cheerio. I used a faster one. Here's a little script:

import { parse } from 'node-html-parser'

export const LOCALHOST_URL = 'http://localhost:3000'

export async function getActionNo(): Promise<string> {
  const res = await fetch(`${LOCALHOST_URL}/signup`)
  const html = await res.text()
  const $ = parse(html)
  const str = $.querySelector('input[name="$ACTION_1:0"]')
    ?.getAttribute('value')
    ?.toString() as string
  const data = JSON.parse(str)

  return data.id // '0917c6804f07eaf34c42aa6867f90bf00983db90'
}

Upvotes: 2

Related Questions