360 Secure SkillHub
360 安全技能中心

safe-action-advanced

该 Skill 是 next-safe-action 的高级功能文档,说明 .bind() 参数、类型化 metadata、redirect/notFound/forbidden/unauthorized 等框架错误、类型推断工具,以及服务端 action 回调。内容以 TypeScript 代码片段展示,不包含可执行项目、依赖安装或测试。

分类:开发
next-safe-action
热度 0.00
最近更新 2026-10-30 17:10:15

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add next-safe-action/skills/safe-action-advanced
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
safe-action-advanced
description
Use when working with bind arguments, metadata schemas, framework errors (redirect/notFound/forbidden/unauthorized), type inference utilities (InferSafeActionFnInput/Result), or server-level action callbacks

next-safe-action Advanced Features

Overview

Feature Use Case
Bind arguments Pass extra args to actions via .bind() (e.g., resource IDs)
Metadata Attach typed metadata to actions for use in middleware
Framework errors Handle redirect, notFound, forbidden, unauthorized in actions
Type utilities Infer types from action functions and middleware

Server-Level Action Callbacks

The second argument to .action() accepts callbacks that run on the server (not client-side hooks):

export const createPost = authActionClient
  .inputSchema(schema)
  .action(
    async ({ parsedInput, ctx }) => {
      const post = await db.post.create(parsedInput);
      return post;
    },
    {
      onSuccess: async ({ data, parsedInput, ctx, metadata, clientInput }) => {
        // Runs on the server after successful execution
        await invalidateCache("posts");
      },
      onError: async ({ error, metadata, ctx, clientInput, bindArgsClientInputs }) => {
        // error: { serverError?, validationErrors? }
        await logError(error);
      },
      onSettled: async ({ result }) => {
        // Always runs
        await recordMetrics(result);
      },
      onNavigation: async ({ navigationKind }) => {
        // Runs when a framework error (redirect, notFound, etc.) occurs
        console.log("Navigation:", navigationKind);
      },
    }
  );

These are distinct from hook callbacks (useAction({ onSuccess })) — server callbacks run in the Node.js runtime, hook callbacks run in the browser.

throwServerError

Re-throw server errors instead of returning them as result.serverError:

export const myAction = actionClient
  .inputSchema(schema)
  .action(serverCodeFn, {
    throwServerError: true,
    // The handled server error (return of handleServerError) is thrown
  });

Don't confuse this with returnServerError(): throwServerError throws the handled error (post-handleServerError) instead of returning it, while returnServerError(payload) returns a typed expected error in result.serverError, bypassing handleServerError entirely (see the safe-action-client skill's error-handling doc).