next-safe-action
API reference

Types

This page documents all the TypeScript types exported by next-safe-action. Types are exported from the main next-safe-action entry point unless otherwise noted.

Core types

SafeActionResult

The result object returned by every action execution. Modeled as a discriminated union so that at most one of data, serverError, and validationErrors is populated — checking one field narrows the others to undefined.

type SafeActionResult<ServerError, Schema, ShapedErrors, Data> =
	| { data?: undefined; serverError?: undefined; validationErrors?: undefined } // idle / framework navigation
	| { data: Data; serverError?: undefined; validationErrors?: undefined }        // success
	| { data?: undefined; serverError: ServerError; validationErrors?: undefined } // server error
	| { data?: undefined; serverError?: undefined; validationErrors: ShapedErrors }; // validation failure

Prop

Type

In compound-error scenarios where the runtime could otherwise produce multiple populated fields (middleware calling next() twice, or invalid bind args combined with invalid main input), a fixed precedence is applied: validationErrors > serverError > data. See Action result for details.


SafeActionFn

The callable function type returned by .action().

type SafeActionFn<ServerError, Schema, BindArgsSchemas, ShapedErrors, Data> = (
	...clientInputs: [...bindArgsInputs: InferInputArray<BindArgsSchemas>, input: InferInput<Schema>]
) => Promise<SafeActionResult<ServerError, Schema, ShapedErrors, Data>>;

When bind args are defined, they appear as leading parameters. The main input is always the last parameter.


SafeStateActionFn

The callable function type returned by .stateAction().

type SafeStateActionFn<ServerError, Schema, BindArgsSchemas, ShapedErrors, Data> = (
	...clientInputs: [
		...bindArgsInputs: InferInputArray<BindArgsSchemas>,
		prevResult: SafeActionResult<ServerError, Schema, ShapedErrors, Data>,
		input: InferInput<Schema>,
	]
) => Promise<SafeActionResult<ServerError, Schema, ShapedErrors, Data>>;

Same as SafeActionFn but includes prevResult as the second-to-last parameter, before the main input.


Middleware types

MiddlewareFn

The function type for middleware defined via .use() or createMiddleware().define().

type MiddlewareFn<ServerError, Metadata, Ctx, NextCtx> = (opts: {
	clientInput: unknown;
	bindArgsClientInputs: unknown[];
	ctx: Ctx;
	metadata: Metadata;
	next: <NC extends object = {}>(opts?: { ctx?: NC }) => Promise<MiddlewareResult<ServerError, NC>>;
}) => Promise<MiddlewareResult<ServerError, NextCtx>>;

MiddlewareResult

The result type returned by the next() function inside middleware. Carries the same readable fields as SafeActionResult plus execution metadata (navigation kind, parsed inputs, context, success flag).

type MiddlewareResult<ServerError, NextCtx> = {
	data?: any;
	serverError?: ServerError;
	validationErrors?: any;
	navigationKind?: NavigationKind;
	parsedInput?: unknown;
	bindArgsParsedInputs?: unknown[];
	ctx?: object;
	success: boolean;
};

This is intentionally a flat object rather than an intersection with SafeActionResult. Because SafeActionResult is now a discriminated union, intersecting it would prevent middleware from mutating data/serverError/validationErrors while the chain executes. The set of readable fields is unchanged from previous versions.

Prop

Type


Server code types

ServerCodeFn

The function type for the server code passed to .action().

type ServerCodeFn<Metadata, Ctx, Schema, BindArgsSchemas, Data> = (args: {
	parsedInput: InferOutput<Schema> | undefined;
	clientInput: InferInput<Schema> | undefined;
	bindArgsParsedInputs: InferOutputArray<BindArgsSchemas>;
	bindArgsClientInputs: InferInputArray<BindArgsSchemas>;
	ctx: Ctx;
	metadata: Metadata;
}) => Promise<Data>;

StatefulServerCodeFn

The function type for the server code passed to .stateAction(). Same as ServerCodeFn but with a second utils argument.

type StatefulServerCodeFn<ServerError, Metadata, Ctx, Schema, BindArgsSchemas, ShapedErrors, Data> = (
	args: {
		parsedInput: InferOutput<Schema> | undefined;
		clientInput: InferInput<Schema> | undefined;
		bindArgsParsedInputs: InferOutputArray<BindArgsSchemas>;
		bindArgsClientInputs: InferInputArray<BindArgsSchemas>;
		ctx: Ctx;
		metadata: Metadata;
	},
	utils: {
		prevResult: SafeActionResult<ServerError, Schema, ShapedErrors, Data>;
	}
) => Promise<Data>;

Configuration types

CreateClientOpts

Options passed to createSafeActionClient().

type CreateClientOpts<ErrorsFormat, ServerError, MetadataSchema> = {
	defineMetadataSchema?: () => MetadataSchema;
	handleServerError?: HandleServerErrorFn<ServerError, MetadataSchema>;
	defaultValidationErrorsShape?: ErrorsFormat;
	throwValidationErrors?: boolean;
};

ActionCallbacks

Server-side callbacks and options passed as the second argument to .action() and .stateAction().

type ActionCallbacks<ServerError, Metadata, Ctx, Schema, BindArgsSchemas, ShapedErrors, Data> = {
	throwServerError?: boolean;
	throwValidationErrors?: boolean | {
		overrideErrorMessage: (validationErrors: ShapedErrors) => Promise<string>;
	};
	onSuccess?: (args: { data?, metadata, ctx?, clientInput, bindArgsClientInputs, parsedInput, bindArgsParsedInputs }) => Promise<unknown>;
	onNavigation?: (args: { metadata, ctx?, clientInput, bindArgsClientInputs, navigationKind }) => Promise<unknown>;
	onError?: (args: { error, metadata, ctx?, clientInput, bindArgsClientInputs }) => Promise<unknown>;
	onSettled?: (args: { result, metadata, ctx?, clientInput, bindArgsClientInputs, navigationKind? }) => Promise<unknown>;
};

HandleServerErrorFn

The type for the handleServerError callback.

type HandleServerErrorFn<ServerError, MetadataSchema> = (
	error: Error,
	utils: ServerErrorFunctionUtils<MetadataSchema>
) => MaybePromise<ServerError>;

ServerErrorFunctionUtils

Utils passed to handleServerError.

type ServerErrorFunctionUtils<MetadataSchema> = {
	clientInput: unknown;
	bindArgsClientInputs: unknown[];
	ctx: object;
	metadata: InferOutput<MetadataSchema> | undefined;
};

Hook result types

These types describe the result shape within each branch of the hook return discriminated union. They are exported from next-safe-action/hooks.

NormalizeActionResult

Collapses the void-success branch of a SafeActionResult union. When an action returns nothing (void), the { data: void } branch is dropped so that result.data is exactly undefined rather than void | undefined. Applied automatically to hook result and executeAsync return types.

type NormalizeActionResult<R> = R extends { data: infer D }
	? [D] extends [void]
		? Exclude<R, { data: D }>
		: R
	: R;

When Data is not void, the type passes through unchanged.


HookIdleResult

The result shape when no action has completed yet (idle, executing, navigated). All fields are undefined.

type HookIdleResult = {
	data?: undefined;
	serverError?: undefined;
	validationErrors?: undefined;
};

HookSuccessResult

The result shape for the success branch. For void-returning actions, collapses to HookIdleResult.

type HookSuccessResult<Data> = [Data] extends [void]
	? HookIdleResult
	: { data: Data; serverError?: undefined; validationErrors?: undefined };

HookErrorResult

The result shape for the error branch. Includes the idle shape for thrown errors (where result is {} and the error is captured internally).

type HookErrorResult<ServerError, ShapedErrors> =
	| HookIdleResult
	| { data?: undefined; serverError: ServerError; validationErrors?: undefined }
	| { data?: undefined; serverError?: undefined; validationErrors: ShapedErrors };

Validation error types

ValidationErrors

The formatted validation errors type, mirroring the schema structure.

type ValidationErrors<Schema> = Schema extends StandardSchemaV1
	? InferOutput<Schema> extends PrimitiveOrArray
		? { _errors?: string[] }
		: { _errors?: string[] } & SchemaErrors<InferOutput<Schema>>
	: undefined;

Each level of the schema can have an _errors array. Nested objects create nested error objects.


FlattenedValidationErrors

The flattened validation errors type, with top-level formErrors and fieldErrors.

type FlattenedValidationErrors<VE> = {
	formErrors: string[];
	fieldErrors: {
		[K in keyof Omit<VE, "_errors">]?: string[];
	};
};

HandleValidationErrorsShapeFn

Function type for custom validation error shaping.

type HandleValidationErrorsShapeFn<Schema, BindArgsSchemas, Metadata, Ctx, ShapedErrors> = (
	validationErrors: ValidationErrors<Schema>,
	utils: {
		clientInput: InferInput<Schema> | undefined;
		bindArgsClientInputs: InferInputArray<BindArgsSchemas>;
		metadata: Metadata;
		ctx: Ctx;
	}
) => Promise<ShapedErrors>;

Union type representing framework navigation functions.

type NavigationKind = "redirect" | "notFound" | "forbidden" | "unauthorized" | "other";

Enums and constants

ValidationErrorsFormat

The default validation errors shape type.

type ValidationErrorsFormat = "formatted" | "flattened";

Utility types

Prettify

Makes complex intersection types readable in IDE hover tooltips.

type Prettify<T> = { [K in keyof T]: T[K] } & {};

MaybePromise

Accepts a value or a promise of a value.

type MaybePromise<T> = Promise<T> | T;

MaybeArray

Accepts a value or an array of values.

type MaybeArray<T> = T | T[];

See also

  • Type utilities: Infer* types for extracting types from actions and clients
  • Action result: understanding SafeActionResult
  • Hooks API: HookCallbacks, HookActionStatus, and hook return types

On this page