Summary:
To summarize, the key step is to obtain and parse the actionId
.
Understanding Server Actions
Let's delve into what server actions actually entail. Essentially, a server action is a specialized function present in Next.js (and React.js) that gets triggered on the server side when a specific user event occurs.
In Next.js, server actions can be utilized in both server and client components. In a server component, it can be directly implemented. Regardless of the approach, you need to define it using the directive "use server"
.
Below is an illustration showcasing server components:
app/page.tsx
export default function Page() {
// Server Action
async function create() {
"use server"
// Mutate data
}
return '...'
}
For client components, these actions must be defined in a separate file as demonstrated below:
actions/actions.ts
'use server'
export async function create() {
// Mutate data
}
If you want to access data from a form submission, you should pass a form submission event to the action along with the action
prop to the component:
export default function Page() {
async function createInvoice(formData: FormData) {
'use server'
const rawFormData = {
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
}
// mutate data
// revalidate cache
}
return <form action={createInvoice}>...</form>
}
The above examples have been adapted from the Next.js documentation (License MIT)
Sending a Request
In the preceding section, we established some prerequisites that need to be emulated for testing these actions:
- The
FormData
object
- The location of the action
- Other HTTP headers
To understand the inner workings of Next.js server actions, let's consider how they operate...
When running server actions, Next.js generates server endpoints that accept POST requests. To encapsulate this process, follow these steps:
- Create a function named
setActionId
which accepts an action and caches it
- Create a function named
getCurrentActionId
to retrieve the current action id
- Establish a
GET
endpoint to output the result of getCurrentActionId
- Subsequently, dispatch a
POST
request like before but include a new header next-action
with the value obtained from this API route
helpers/setActionId
const saveActionId = (actionId: string): void => {
if(!proccess.env.LOAD_TEST) {
return;
}
if(!fs.existSync(".tests") {
fs.mkdirSync(".tests");
}
fs.writeFileSync(".tests/actions", actionId.split("_")[2]);
}
helpers/getActionId
const getCurrentActionId() => {
const id = fs.readFileSync(".testsAction");
fs.rmSync(".tests/actions");
return id;
}
One limitation to keep in mind with this method is that only one action can be tested at a time.
We trust this information proves valuable to you.