next-safe-action is a library designed for Next.js projects to create type-safe and validated Server Actions. It leverages modern Next.js, React, and TypeScript features to ensure end-to-end type safety from client-side component calls to server-side action execution. The current stable version is 8.5.2, with minor and patch releases occurring frequently to refine types, add features, and improve developer experience. Key differentiators include robust input/output validation, a flexible middleware system for authorization or logging, advanced server error handling, and support for optimistic updates, making it a powerful tool for building reliable and predictable data mutations in Next.js applications.
npm install next-safe-actionVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a type-safe server action with input validation using Zod and then execute it from a client component using the `useAction` hook, handling loading states and displaying errors.
Consult the official v7 to v8 migration guide at `https://next-safe-action.dev/docs/migrations/v7-to-v8` to update action client initialization and action definitions.
Ensure your client-side logic correctly handles the narrowed types. When `result.data` is present, `serverError` and `validationErrors` will be `undefined` (and vice-versa). This improves type safety but might require adjustments to conditional checks.
Always use ES module `import` syntax (e.g., `import { createSafeActionClient } from 'next-safe-action';`). Ensure your Next.js project and `tsconfig.json` are configured for ESM.Add the `'use client';` directive at the top of any file defining a component that calls `useAction`.
Verify that `next-safe-action` is installed correctly (`npm i next-safe-action`) and ensure you are using ES module imports (`import ... from 'next-safe-action';`). If using CommonJS in Node.js, you might need to configure your project for ESM or use a bundler that handles ESM correctly.
The `useAction` hook must be imported from the `/hook` subpath: `import { useAction } from 'next-safe-action/hook';`.Always conditionally access properties of `result` and its nested objects, e.g., `result?.validationErrors?.fieldName` or `if (result.validationErrors) { /* handle errors */ }`. With v8.5.0+, leverage the discriminated union by checking `result.validationErrors` first.