SafeFn
Running a SafeFn

As an action

When you're intending to call the SafeFn from the client, such as via a server action or through an API route, you can use the createAction() method. This returns a function that returns an ActionResult. This is done as NeverThrow's Result type cannot be serialized and sent to the client.

When using the useServerAction() hook from safe-fn-react, this is automatically converted back to a ResultAsync for you.

const mySafeFn = SafeFn.new().handler(() => {
  return ok("Success");
});
 
const action = mySafeFn.createAction();

The required argument is either the input type of the input schema if you defined one, or the type set through .unparsedInput<T>(). This is merged that of the parent SafeFn if there is one.

const mySafeFn = SafeFn.new()
  .input(z.object({ name: z.string() }))
  .handler((args) => {
    return ok(`Hello, ${args.unparsedInput.name}!`);
  });
 
const res = mySafeFn.createAction()({ firstName: "World" });
// Error:'firstName' does not exist in type '{ name: string; }

Return type

See the dedicated page for the return type of createAction().

On this page