Our application is built on NextJs, if we have to perform load testing by calling APIs, how we would be calling server actions using an API itself ?
Calling server actions require a next-action
parameter in the request header, and how one can genereate one? Without this parameter, it will redirect to a page.
Here is an image below to see the next-action header.
The server action actually calls the POST
method API with the same endpoint as the page.
Sure, we can copy the next-action
header from the browser console, but we cannot do it everytime.
Also whenever a new build generates, it generates a different hash. So it is very difficult to replicate using an API for load testing or any scripting purposes.
Anyone has an idea how to achieve this?
I tried asking AI, but it was giving wrong answers giving random path in the next
module, hence throwing error.
2
Answers
You could create a middleware that adds the required
next-action
header to requests coming from your load testing tool. This would require you to generate and store the correct hash somewhere accessible to the middleware.I found this solution hope it works.
TLDR:
You need to obtain and parse the
actionId
What are server actions
First let’s go in depth on what server action is. In concept it is simple, a server action is a special function within Next.js (and React.js) that runs on the server when some type of user triggered event happens.
In Next.js server action can be used both in server and client components. In a server component you can use it directly. Either way you must define it with the
"use server"
directive.Here is an example with server components:
app/page.tsx
In client components you must define them in a separate file:
actions/actions.ts
To access data from say a form submission you can pass an form submission event to the action as well as
action
prop to the component:These examples were provided and adapted from the Next.js docs (License MIT)
Sending a request
In the last section we have established a few baselines we need to mock in order to test these actions:
FormData
To find these let’s take a look at how Next.js server actions work under the hood…
To run server actions Next.js generates server endpoints that accept POST requests. So in short here is how I would do it:
getActionId
function that only runs whenprocess.env.loadTest
has a value. This function should be called in the server action you want to testactionId
in a plaintext fileGET
endpoint to return theactionId
and send a request to it in your load test callsPOST
request like before with the newnext-action
header as the value returned from this functionIf you are using a specific load testing solution I can provide some code for you to get started with!
Hope this helps.