Introduction
zsa
is the best library for building typesafe server actions in NextJS. Built for a simple, scalable developer experience. Some majors features include...
- Validated inputs/outputs with zod (hence the name Zod Server Actions)
- Procedures (aka middleware) that pass context to your server actions
- React Query integration for querying server actions in client components
and much more!
To get started, you can install zsa
using any package manager:
Zod provides a simple way to define and validate types in your code.
Creating your first action
There's plenty of functionality with zsa
, but to start, here is how you make a simple, validated server action:
(we know this function is silly but it gets the point across)
Let's break down the code:
createServerAction
initializes a server action.input
sets the input schema for the action using a Zod schema.handler
sets the handler function for the action. The input is automatically validated based on the input schema.
A ZSAError
with the code INPUT_PARSE_ERROR
will be returned if the
handler's input is does not match input schema.
Calling from the server
Server actions can also be called directly from the server without the need for a try/catch block.
The action will return either [data, null]
on success or [null, err]
on error.
Calling from the client
The most lightweight way to call your server action is to just call it! That is the beauty of server actions.
However, usually you will want to use the useServerAction
hook to make your life easier.
Server actions come with built-in loading states, making it easy to handle asynchronous operations. Here's an example of using the incrementNumberAction
as a mutation:
useServerAction
allows you to use this server action from within your client components.execute
executes the server action endpoint with the typesafe input directly fromonClick
.
Here is the result:
Increment Number
Count:
Thats just the beginning... Continue reading to learn more about zsa
!
To use server actions for querying/refetching data from the client side, visit the Client Side Usage section.