Migration from v3 to v4
Version 4.x.x of next-safe-action introduced many improvements, some fixes, and some breaking changes.
This guide will help you migrate from v3 to v4, hopefully without too much trouble.
note
You can continue to use version 3 of the library if you want to. There are no security implications, since version 4 introduced some new features and changed some functions and properties names. No security patches were committed to v4, at least for the time being, so v3 is currently still safe to use. You'll not get new features in v3, though.
BREAKING CHANGES
Safe action client
- buildContext()function is now called- middleware(), and it can still return a context object.
- serverErrorLogFunction()function is now called- handleServerErrorLog().
Hooks
- resobject is now called- result.
- Action status before was reported through returned hasExecuted,isExecuting,hasSucceededandhasErroredproperties. Now there's a single property of type string calledstatusthat contains the current action status, and it can be"idle","executing","hasSucceeded"or"hasErrored".
- Reorganized callbacks arguments for onSuccessandonError:- from onSuccess(data, reset, input)toonSuccess(data, input, reset)
- from onError(error, reset, input)toonError(error, input, reset)
 
- from 
- useOptimisticActionjust required a safe action and an initial optimistic state before. Now it requires a- reducerfunction too, that determines the behavior of the optimistic state update when the- executefunction is called. Also, now only one input argument is required by- execute, instead of two. The same input passed to the actual safe action is now passed to the- reducerfunction too, as the second argument (- input). More information about this hook can be found here.
Types
- ActionDefinitionis now called- ServerCode.
- HookResis now called- HookResult.
- ClientCalleris now called- SafeAction.
New features
Hooks
- Added optional onSettledcallback foruseActionanduseOptimisticActionhooks. It gets executed if the action succeeds or fails, afteronSuccessandonError.
Fixes
- Fixed an issue with Zod input validation parsing. Before, if an async superRefine()was used when defining the schema, the validation would fail, resulting in aserverErrorresponse for the client. Now the validation is done throughsafeParseAsync(), so the problem is gone.
Misc
Safe action client
- Now Contextreturned bymiddleware()(previously calledbuildContext()in v3) is not required to be an object anymore, it can be of any type.
Hooks
- Before, you had to return an object from actions you wanted to execute via useOptimisticActionhook. Now, with the new exposedreducerfunction (see above), you can return anything you want from action server code body.