next-action-plus 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +862 -280
  2. package/dist/auth/authjs.d.ts +23 -0
  3. package/dist/auth/authjs.js +18 -0
  4. package/dist/auth/better-auth.d.ts +34 -0
  5. package/dist/auth/better-auth.js +17 -0
  6. package/dist/auth/clerk.d.ts +20 -0
  7. package/dist/auth/clerk.js +17 -0
  8. package/dist/auth/iron-session.d.ts +21 -0
  9. package/dist/auth/iron-session.js +18 -0
  10. package/dist/auth/kinde.d.ts +25 -0
  11. package/dist/auth/kinde.js +19 -0
  12. package/dist/auth/supabase.d.ts +29 -0
  13. package/dist/auth/supabase.js +17 -0
  14. package/dist/auth/workos.d.ts +25 -0
  15. package/dist/auth/workos.js +17 -0
  16. package/dist/authorize/casl.d.ts +14 -0
  17. package/dist/authorize/casl.js +10 -0
  18. package/dist/authorize/cerbos.d.ts +26 -0
  19. package/dist/authorize/cerbos.js +10 -0
  20. package/dist/authorize/openfga.d.ts +20 -0
  21. package/dist/authorize/openfga.js +10 -0
  22. package/dist/authorize/oso.d.ts +20 -0
  23. package/dist/authorize/oso.js +10 -0
  24. package/dist/authorize/permit.d.ts +14 -0
  25. package/dist/authorize/permit.js +10 -0
  26. package/dist/authorize.d.ts +11 -0
  27. package/dist/authorize.js +2 -0
  28. package/dist/chunk-2INYDUJR.js +16 -0
  29. package/dist/chunk-A55FM7D6.js +53 -0
  30. package/dist/chunk-GFGIJNSY.js +19 -0
  31. package/dist/chunk-IFAKJ72B.js +16 -0
  32. package/dist/codemod/bin.js +169 -0
  33. package/dist/concurrency/lock/memory.d.ts +5 -0
  34. package/dist/concurrency/lock/memory.js +1 -0
  35. package/dist/concurrency/lock/postgres.d.ts +9 -0
  36. package/dist/concurrency/lock/postgres.js +45 -0
  37. package/dist/concurrency/lock/redis.d.ts +9 -0
  38. package/dist/concurrency/lock/redis.js +30 -0
  39. package/dist/concurrency.d.ts +21 -0
  40. package/dist/concurrency.js +48 -0
  41. package/dist/conformance.d.ts +29 -0
  42. package/dist/conformance.js +139 -0
  43. package/dist/gate.d.ts +17 -0
  44. package/dist/gate.js +2 -0
  45. package/dist/i18n/next-intl.d.ts +12 -0
  46. package/dist/i18n/next-intl.js +11 -0
  47. package/dist/idempotency.d.ts +12 -0
  48. package/dist/idempotency.js +28 -0
  49. package/dist/index-BSA9a_EW.d.ts +22 -0
  50. package/dist/index-C3Ra6AYj.d.ts +37 -0
  51. package/dist/index-CZFS0TSh.d.ts +53 -0
  52. package/dist/index-CuAEDv-H.d.ts +64 -0
  53. package/dist/index-DJ2Ox9am.d.ts +31 -0
  54. package/dist/index-DV3R2g7H.d.ts +41 -0
  55. package/dist/index.d.ts +196 -192
  56. package/dist/index.js +189 -278
  57. package/dist/kv/memory.d.ts +5 -0
  58. package/dist/kv/memory.js +27 -0
  59. package/dist/kv/redis.d.ts +9 -0
  60. package/dist/kv/redis.js +23 -0
  61. package/dist/queue/bullmq.d.ts +18 -0
  62. package/dist/queue/bullmq.js +14 -0
  63. package/dist/queue/inngest.d.ts +18 -0
  64. package/dist/queue/inngest.js +14 -0
  65. package/dist/queue/qstash.d.ts +19 -0
  66. package/dist/queue/qstash.js +14 -0
  67. package/dist/queue/trigger.d.ts +16 -0
  68. package/dist/queue/trigger.js +11 -0
  69. package/dist/rate/limit/arcjet.d.ts +19 -0
  70. package/dist/rate/limit/arcjet.js +15 -0
  71. package/dist/rate/limit/unkey.d.ts +25 -0
  72. package/dist/rate/limit/unkey.js +14 -0
  73. package/dist/rate/limit/upstash.d.ts +18 -0
  74. package/dist/rate/limit/upstash.js +15 -0
  75. package/dist/rate/limit.d.ts +12 -0
  76. package/dist/rate/limit.js +17 -0
  77. package/dist/react.d.ts +40 -0
  78. package/dist/react.js +110 -0
  79. package/dist/security/origin.d.ts +11 -0
  80. package/dist/security/origin.js +21 -0
  81. package/dist/security/redact.d.ts +9 -0
  82. package/dist/security/redact.js +15 -0
  83. package/dist/security/secret.d.ts +6 -0
  84. package/dist/security/secret.js +13 -0
  85. package/dist/spec.d.ts +6 -0
  86. package/dist/spec.js +1 -0
  87. package/dist/telemetry/otel.d.ts +11 -0
  88. package/dist/telemetry/otel.js +25 -0
  89. package/dist/telemetry/pino.d.ts +12 -0
  90. package/dist/telemetry/pino.js +18 -0
  91. package/dist/telemetry/sentry.d.ts +16 -0
  92. package/dist/telemetry/sentry.js +11 -0
  93. package/package.json +325 -72
  94. package/dist/index.js.map +0 -1
package/README.md CHANGED
@@ -1,280 +1,862 @@
1
- # next-action-plus
2
-
3
- ![next-action-plus logo](https://raw.githubusercontent.com/muhgholy/next-action-plus/main/assets/next-action-plus.svg)
4
-
5
- **next-action-plus** is a tiny TypeScript library for **type-safe Next.js Server Actions**.
6
-
7
- You write a server action like you always do. You optionally add a schema. You get:
8
-
9
- - Input validation (Zod compatible, but schema-agnostic)
10
- - Correct `parsedInput` type inference
11
- - A native-feeling API: `.schema(...).action(async (...) => ...)`
12
-
13
- No framework lock-in. No new mental model.
14
-
15
- ## Table of contents
16
-
17
- - [Why next-action-plus](#why-next-action-plus)
18
- - [Install](#install)
19
- - [Quick start](#quick-start)
20
- - [Error handling](#error-handling)
21
- - [Examples](#examples)
22
- - [Next.js Server Action](#nextjs-server-action)
23
- - [Client Component usage](#client-component-usage)
24
- - [FormData + File uploads](#formdata--file-uploads)
25
- - [Middleware (ctx)](#middleware-ctx)
26
- - [Schema-agnostic validation](#schema-agnostic-validation)
27
- - [FAQ](#faq)
28
- - [Release](#release)
29
-
30
- ## Why next-action-plus
31
-
32
- Next.js Server Actions are great because they are simple: a function that runs on the server.
33
- But when you accept user input, you usually need:
34
-
35
- - validation
36
- - safe parsing
37
- - accurate types in the handler
38
-
39
- next-action-plus keeps the **server action function shape** and adds **type-safe input parsing**.
40
- You can treat your action like a normal function, and you still get strict TypeScript inference.
41
-
42
- ## Install
43
-
44
- ```bash
45
- npm i next-action-plus
46
- ```
47
-
48
- If you want Zod schemas, also install:
49
-
50
- ```bash
51
- npm i zod
52
- ```
53
-
54
- ## Quick start
55
-
56
- ```ts
57
- import { createActionPlus } from 'next-action-plus';
58
- import { z } from 'zod';
59
-
60
- export const sayHello = createActionPlus()
61
- .schema(z.object({ name: z.string().min(1) }))
62
- .action(async ({ parsedInput }) => {
63
- return { message: `Hello ${parsedInput.name}` };
64
- });
65
- ```
66
-
67
- ### What you get
68
-
69
- - `sayHello` is still “just a function” you can call.
70
- - `parsedInput` is inferred from your schema.
71
- - The return type is inferred from your handler.
72
-
73
- ## Error handling
74
-
75
- If schema validation fails, the action **throws** an `Error`.
76
-
77
- The error message is intentionally short and looks like:
78
-
79
- ```txt
80
- Input (name) is error: String must contain at least 1 character(s)
81
- ```
82
-
83
- Notes:
84
-
85
- - Only the **first** validation issue is used to build the message.
86
- - The thrown error is an `ActionPlusValidationError` (extends `Error`) with a developer-friendly payload.
87
- - The original validator error is preserved on `error.cause`.
88
- - Normalized issues are available on `error.issues`.
89
-
90
- ```ts
91
- try {
92
- await sayHello({ name: '' });
93
- } catch (error) {
94
- // error.message => "Input (name) is error: ..."
95
- // (error as ActionPlusValidationError).code => "VALIDATION_ERROR"
96
- // (error as ActionPlusValidationError).issues => [{ path, message, raw }]
97
- // (error as any).cause => original validator error (e.g. ZodError)
98
- }
99
- ```
100
-
101
- ### Customizing errors (options)
102
-
103
- `createActionPlus` accepts options to control logging and customize thrown errors.
104
-
105
- ```ts
106
- import { createActionPlus } from 'next-action-plus';
107
-
108
- export const client = createActionPlus({
109
- logger: false,
110
- formatValidationError: ({ message, issues, error }) => {
111
- const e = new Error(message);
112
- (e as any).issues = issues;
113
- (e as any).cause = error;
114
- return e;
115
- },
116
- onError: ({ phase, error }) => {
117
- // report errors (Sentry, etc)
118
- // phase: "validation" | "middleware" | "handler"
119
- void error;
120
- },
121
- });
122
- ```
123
-
124
- ## Examples
125
-
126
- ### Next.js Server Action
127
-
128
- This keeps the native Server Action feel.
129
-
130
- ```ts
131
- import 'server-only';
132
- import { createActionPlus } from 'next-action-plus';
133
- import { z } from 'zod';
134
-
135
- export const updateProfile = createActionPlus()
136
- .schema(z.object({ displayName: z.string().min(2) }))
137
- .action(async ({ parsedInput }) => {
138
- // parsedInput.displayName is string
139
- return { ok: true };
140
- });
141
- ```
142
-
143
- ### Client Component usage
144
-
145
- You can import a Server Action into a Client Component and call it like a normal async function.
146
- Next.js runs it on the server.
147
-
148
- ```tsx
149
- 'use client';
150
-
151
- import { useState, useTransition } from 'react';
152
- import { sayHello } from '@/app/actions';
153
-
154
- export function SayHelloClient() {
155
- const [name, setName] = useState('');
156
- const [message, setMessage] = useState<string | null>(null);
157
- const [pending, startTransition] = useTransition();
158
-
159
- return (
160
- <div>
161
- <input value={name} onChange={e => setName(e.target.value)} placeholder='Ada' />
162
- <button
163
- disabled={pending}
164
- onClick={() =>
165
- startTransition(async () => {
166
- const result = await sayHello({ name });
167
- setMessage(result.message);
168
- })
169
- }
170
- >
171
- {pending ? 'Sending…' : 'Say hello'}
172
- </button>
173
- {message ? <p>{message}</p> : null}
174
- </div>
175
- );
176
- }
177
- ```
178
-
179
- The snippets above are the full examples.
180
-
181
- ### FormData + File uploads
182
-
183
- Works with `FormData` and `File` using `zod-form-data`.
184
-
185
- If you chain multiple schemas and the input is a `FormData`, next-action-plus will first try to find a schema that can parse the `FormData` into a plain object, then validate the remaining schemas against that object.
186
-
187
- ```ts
188
- import { createActionPlus } from 'next-action-plus';
189
- import { zfd } from 'zod-form-data';
190
-
191
- export const uploadAvatar = createActionPlus()
192
- .schema(
193
- zfd.formData({
194
- avatar: zfd.file(),
195
- }),
196
- )
197
- .action(async ({ parsedInput }) => {
198
- // parsedInput.avatar is File
199
- return { filename: parsedInput.avatar.name };
200
- });
201
- ```
202
-
203
- ### Middleware (ctx)
204
-
205
- Add data to context in a type-safe way.
206
-
207
- Validation runs first, then middleware runs, then your handler runs.
208
-
209
- ```ts
210
- import { createActionPlus } from 'next-action-plus';
211
- import { z } from 'zod';
212
-
213
- const client = createActionPlus().use(async ({ next }) => next({ ctx: { userId: 'u_123' } }));
214
-
215
- export const deletePost = client.schema(z.object({ postId: z.string() })).action(async ({ parsedInput, ctx }) => {
216
- // ctx.userId is string
217
- // parsedInput.postId is string
218
- return { ok: true };
219
- });
220
- ```
221
-
222
- ### Schema-agnostic validation
223
-
224
- You are not forced into one validator.
225
-
226
- Supported schema shapes:
227
-
228
- - Zod (`parse` / `parseAsync`)
229
- - Generic `{ parse(...) }` and `{ parseAsync(...) }`
230
- - Standard Schema v1 (`~standard.validate`)
231
-
232
- If you already have a schema system, you can plug it in.
233
-
234
- #### Schema chaining
235
-
236
- You can chain multiple schemas. If they return objects, outputs are merged.
237
-
238
- ```ts
239
- import { createActionPlus } from 'next-action-plus';
240
-
241
- const s1 = { parse: (_: unknown) => ({ a: 'a' }) };
242
- const s2 = { parse: (_: unknown) => ({ b: 2 }) };
243
-
244
- export const demo = createActionPlus()
245
- .schema(s1)
246
- .schema(s2)
247
- .action(async ({ parsedInput }) => {
248
- // parsedInput is { a: string; b: number }
249
- return parsedInput;
250
- });
251
- ```
252
-
253
- ## FAQ
254
-
255
- ### Is next-action-plus only for Next.js?
256
-
257
- No. It is built for the Server Actions style, but it runs in any Node 20+ runtime.
258
-
259
- ### Do I need to learn a new pattern?
260
-
261
- No. The API is intentionally small: `createActionPlus() → .schema() → .use() → .action()`.
262
-
263
- ### Can I validate `FormData`?
264
-
265
- Yes. Use `zod-form-data` (see [FormData + File uploads](#formdata--file-uploads)).
266
-
267
- ### Does it change my return types?
268
-
269
- No. The returned action function keeps the exact return type of your handler.
270
-
271
- ### Can I chain multiple schemas?
272
-
273
- Yes. Multiple schemas can validate the same base input. If they produce objects, outputs are merged.
274
-
275
- ## Release
276
-
277
- This repository ships with `semantic-release`.
278
-
279
- - Push Conventional Commits to `main`
280
- - GitHub Actions runs `npm test`, `npm run build`, then publishes
1
+ # next-action-plus
2
+
3
+ ![next-action-plus logo](https://raw.githubusercontent.com/muhgholy/next-action-plus/main/assets/next-action-plus.svg)
4
+
5
+ **next-action-plus is a TypeScript library for type-safe, secure-by-default Next.js Server Actions.** You build each action from a small chain: validate the input with any [Standard Schema](https://standardschema.dev) validator (Zod, Valibot, ArkType, Effect Schema, Yup, or your own), check who is calling with a gate, add middleware, and write the handler. The action stays a plain async function you can import into a Client Component, pass to `<form action>`, or call from a test.
6
+
7
+ What makes it different from wrapping Server Actions by hand:
8
+
9
+ - **Secure by default.** An action without an auth gate or an explicit `.public()` is a type error, because every Server Action is a public POST endpoint.
10
+ - **Nothing hardcoded.** Validators, the result shape, error messages, auth, rate limits, locks, queues and telemetry are all small contracts. Use our adapters or write your own in a few lines.
11
+ - **Types that follow your schema exactly.** Unions, discriminated unions, tuples, primitives and transforms come through unchanged.
12
+ - **Concurrency control.** Queue, drop, latest-wins, keep-latest or dedupe calls per key, across server instances.
13
+
14
+ ## Table of contents
15
+
16
+ - [What is in the package](#what-is-in-the-package)
17
+ - [Install](#install)
18
+ - [Quick start](#quick-start)
19
+ - [How an action runs](#how-an-action-runs)
20
+ - [Defining actions](#defining-actions)
21
+ - [Middleware and plugins](#middleware-and-plugins)
22
+ - [Responses: your own result shape](#responses-your-own-result-shape)
23
+ - [Errors](#errors)
24
+ - [Security](#security)
25
+ - [Concurrency](#concurrency)
26
+ - [Adapters](#adapters)
27
+ - [Writing your own adapter](#writing-your-own-adapter)
28
+ - [React](#react)
29
+ - [Testing your actions](#testing-your-actions)
30
+ - [TypeScript tips](#typescript-tips)
31
+ - [FAQ](#faq)
32
+ - [Migrating from v1](#migrating-from-v1)
33
+
34
+ ## What is in the package
35
+
36
+ Everything ships in one package. Each feature has its own import path, so you only bundle what you use, and vendor SDKs are never imported by the library: adapters take your client as a parameter.
37
+
38
+ | Import path | What it gives you |
39
+ |---|---|
40
+ | `next-action-plus` | `actionCreate`, `errorCreate`, `errorGet`, `formDecode`, `schemaParse`, `responseDefine`, `responseTuple`, `responseResult`, `responseProblem`, all types |
41
+ | `next-action-plus/gate` | `gateCreate`: find the user, put them on `ctx.user`, satisfy the client gate |
42
+ | `next-action-plus/auth/*` | Gates for `clerk`, `better-auth`, `authjs`, `supabase`, `kinde`, `iron-session`, `workos` (experimental) |
43
+ | `next-action-plus/authorize` | `authorizeCreate`: RBAC, ABAC or ReBAC checks after the gate |
44
+ | `next-action-plus/authorize/*` | `cerbos`, `permit`, `casl` (experimental), `openfga` (experimental), `oso` (experimental) |
45
+ | `next-action-plus/rate/limit` | `rateLimitCreate`, plus `upstash`, `arcjet` and `unkey` (experimental) limiters |
46
+ | `next-action-plus/concurrency` | `concurrencyCreate`: parallel, queue, drop, latest, keepLatest, dedupe |
47
+ | `next-action-plus/concurrency/lock/*` | `memory`, `redis`, `postgres` locks with fencing tokens |
48
+ | `next-action-plus/kv/*` | `memory` and `redis` key-value stores |
49
+ | `next-action-plus/idempotency` | `idempotencyCreate`: replay a retried request instead of running it twice |
50
+ | `next-action-plus/queue/*` | `bullmq`, `inngest`, `qstash`, `trigger` background job adapters |
51
+ | `next-action-plus/telemetry/*` | `otel` (OpenTelemetry spans), `sentry`, `pino` |
52
+ | `next-action-plus/i18n/next-intl` | Translated error messages |
53
+ | `next-action-plus/security/*` | `origin` (strict CSRF guard), `redact` (safe log copies), `secret` (constant-time compare) |
54
+ | `next-action-plus/react` | `useAction`: status, callbacks, optimistic state, client-side strategies |
55
+ | `next-action-plus/spec` | The contracts, types only, for writing adapters |
56
+ | `next-action-plus/conformance` | Vitest suites that check your own adapters |
57
+ | `npx next-action-plus codemod v2` | Upgrades a v1 project |
58
+
59
+ ## Install
60
+
61
+ ```bash
62
+ npm i next-action-plus
63
+ ```
64
+
65
+ Then install the validator you like, for example `npm i zod`. No validator is bundled.
66
+
67
+ | Requirement | Version |
68
+ |---|---|
69
+ | Next.js | 15.1 or newer (tested on 16.4) |
70
+ | React | 19 (for `next-action-plus/react`) |
71
+ | TypeScript | 5.5 or newer (tested on 5.5, 6 and 7) |
72
+ | Node.js | 20 or newer |
73
+ | Validator | Any Standard Schema v1 library: Zod 3.24+ or 4, Valibot 1, ArkType 2, Effect Schema, Yup |
74
+
75
+ The core runs on both the Node.js and the Edge runtime. Adapters that need a server driver (`concurrency/lock/postgres`, `queue/bullmq`) run on Node.js only, because their drivers do.
76
+
77
+ ## Quick start
78
+
79
+ Create a client once, with the gate your app uses:
80
+
81
+ ```ts
82
+ // lib/action.ts
83
+ import { actionCreate } from 'next-action-plus';
84
+ import { gateCreate } from 'next-action-plus/gate';
85
+
86
+ // ** Your own session lookup (cookies, a database, an auth provider...)
87
+ declare const sessionUser: () => Promise<{ id: string; role: 'member' | 'admin' } | null>;
88
+
89
+ export const action = actionCreate();
90
+ export const actionUser = action.use(gateCreate({ user: () => sessionUser() }));
91
+ ```
92
+
93
+ Then write actions in a `'use server'` file:
94
+
95
+ ```ts
96
+ // app/posts/actions.ts
97
+ 'use server';
98
+
99
+ import { z } from 'zod';
100
+ import { actionUser } from '@/lib/action';
101
+
102
+ export const aPostRename = actionUser.input(z.object({ id: z.string(), title: z.string().min(1) })).action(async props => {
103
+ const { input, ctx } = props;
104
+ // ** input is { id: string; title: string }, ctx.user is the signed-in user
105
+ return { id: input.id, title: input.title, by: ctx.user.id };
106
+ });
107
+ ```
108
+
109
+ `aPostRename` is still just an async function. Call it from a Client Component with `await aPostRename({ id, title })`. If the input is wrong it throws a validation error; if nobody is signed in it throws `UNAUTHORIZED`. To get failures back as values instead, add a [response contract](#responses-your-own-result-shape).
110
+
111
+ ## How an action runs
112
+
113
+ The chain runs in the order you write it, so you can always read an action top to bottom:
114
+
115
+ 1. **Limits and decoding.** The raw input is checked against `limit` (depth, keys, string and array length, file size, prototype keys). FormData is decoded into a plain object.
116
+ 2. **Bound args.** `.args([...])` schemas validate the values passed with `.bind()`.
117
+ 3. **Steps, in chain order.** Each `.use()` middleware and the `.input()` validation run where you put them. A middleware before `.input()` sees the raw input; after it, the parsed input.
118
+ 4. **Handler.** It receives `{ input, args, ctx, meta, errors }`.
119
+ 5. **Output.** `.output(schema)` validates and strips the result.
120
+ 6. **Response.** Without a response contract you get the handler's value, and failures throw. With one, success and failure are shaped by your contract.
121
+
122
+ Builders never change. Every method returns a new builder, so a shared client like `actionUser` is safe to extend in many files.
123
+
124
+ ## Defining actions
125
+
126
+ ### `.input(schema)`: any Standard Schema
127
+
128
+ Callers send the schema's input type; the handler gets its output type. Nothing is merged or intersected, so every shape works:
129
+
130
+ ```ts
131
+ import { z } from 'zod';
132
+ import * as v from 'valibot';
133
+ import { type } from 'arktype';
134
+ import { actionCreate } from 'next-action-plus';
135
+
136
+ const action = actionCreate().public();
137
+
138
+ export const aSearch = action.input(z.union([z.string(), z.number()])).action(async props => props.input); // string | number
139
+ export const aMove = action.input(z.tuple([z.number(), z.number()])).action(async props => props.input); // [number, number]
140
+ export const aToggle = action.input(z.boolean()).action(async props => !props.input); // boolean
141
+ export const aAge = action.input(z.object({ age: z.string().transform(Number) })).action(async props => props.input.age); // number
142
+ export const aValibot = action.input(v.object({ id: v.string() })).action(async props => props.input.id);
143
+ export const aArkType = action.input(type({ id: 'string' })).action(async props => props.input.id);
144
+ ```
145
+
146
+ The input argument is required when the schema requires it, and optional when the schema accepts `undefined`. Each action has one `.input()`. Calling it twice is a type error.
147
+
148
+ ### Forms and FormData
149
+
150
+ Pass an action straight to `<form action>`. FormData is decoded before validation, so you write a normal object schema:
151
+
152
+ | Form field name | Decoded as |
153
+ |---|---|
154
+ | `name` | `{ name: 'Ada' }` |
155
+ | `tags` repeated | `{ tags: ['a', 'b'] }` |
156
+ | `tags[]` | `{ tags: ['a', 'b'] }` |
157
+ | `user.email` or `user[email]` | `{ user: { email: '...' } }` |
158
+ | `items[0].id` | `{ items: [{ id: '...' }] }` |
159
+ | a file input | a `File` (empty, unnamed file inputs are skipped) |
160
+ | `$ACTION_*` (added by Next.js) | skipped |
161
+
162
+ ```ts
163
+ 'use server';
164
+
165
+ import { z } from 'zod';
166
+ import { actionCreate } from 'next-action-plus';
167
+
168
+ export const aProfileSave = actionCreate()
169
+ .public()
170
+ .input(z.object({ name: z.string(), avatar: z.instanceof(File), tags: z.array(z.string()) }))
171
+ .action(async props => {
172
+ // ** Form fields arrive as strings: use z.coerce.number() for numbers
173
+ await props.input.avatar.arrayBuffer();
174
+ });
175
+ ```
176
+
177
+ `formDecode({ form })` is exported if you need the same decoding elsewhere.
178
+
179
+ ### `.args([...])`: validate `.bind()` values
180
+
181
+ Values passed with `.bind(null, id)` reach the server without validation, and Next.js does not encrypt them. Give each one a schema:
182
+
183
+ ```ts
184
+ 'use server';
185
+
186
+ import { z } from 'zod';
187
+ import { actionCreate } from 'next-action-plus';
188
+
189
+ export const aCommentAdd = actionCreate()
190
+ .public()
191
+ .args([z.uuid()])
192
+ .input(z.object({ text: z.string().min(1) }))
193
+ .action(async props => {
194
+ const [postId] = props.args;
195
+ return { postId, text: props.input.text };
196
+ });
197
+
198
+ // ** In a component: <form action={aCommentAdd.bind(null, post.id)}>
199
+ ```
200
+
201
+ ### `.output(schema)`: send only what the client may see
202
+
203
+ ```ts
204
+ import { z } from 'zod';
205
+ import { actionCreate } from 'next-action-plus';
206
+
207
+ declare const db: { user: { find: (id: string) => Promise<{ id: string; email: string; passwordHash: string }> } };
208
+
209
+ export const aMe = actionCreate()
210
+ .public()
211
+ .output(z.object({ id: z.string(), email: z.string() }))
212
+ .action(async () => db.user.find('me')); // passwordHash is stripped
213
+ ```
214
+
215
+ If the handler returns something the output schema rejects, that is a server bug. The call fails with `INTERNAL`, never with a validation message about your own data.
216
+
217
+ ### `.errors({...})`, `.meta({...})`, `.public()`
218
+
219
+ ```ts
220
+ import { z } from 'zod';
221
+ import { actionCreate } from 'next-action-plus';
222
+
223
+ export const aInvitationAccept = actionCreate()
224
+ .public()
225
+ .meta({ name: 'invitation.accept' })
226
+ .errors({ EXPIRED: { status: 410, message: 'This invitation has expired' }, SEATS_FULL: { status: 409, data: z.object({ seats: z.number() }) } })
227
+ .input(z.object({ code: z.string() }))
228
+ .action(async props => {
229
+ if (props.input.code === 'old') throw props.errors.EXPIRED();
230
+ if (props.input.code === 'full') throw props.errors.SEATS_FULL({ data: { seats: 5 } });
231
+ return { joined: true };
232
+ });
233
+ ```
234
+
235
+ - **`.errors()`** declares error codes. Handlers and middleware get typed factories, and with a response contract the result type lists every code.
236
+ - **`.meta()`** attaches typed metadata. Middleware and plugins read it for audit logs, span names, rate-limit keys and permission names.
237
+ - **`.public()`** marks an action as intentionally open. It is the only way past the gate without an auth plugin.
238
+
239
+ ### `.actionState(handler)`: for `useActionState`
240
+
241
+ React's `useActionState` calls an action as `(previousState, formData)`. Use `.actionState` and the handler gets `state.previous`:
242
+
243
+ ```ts
244
+ 'use server';
245
+
246
+ import { z } from 'zod';
247
+ import { actionCreate, responseResult } from 'next-action-plus';
248
+
249
+ export const aSubscribe = actionCreate({ response: responseResult() })
250
+ .public()
251
+ .input(z.object({ email: z.email() }))
252
+ .actionState(async props => ({ email: props.input.email, attempts: ((props.state.previous as { data?: { attempts: number } } | null)?.data?.attempts ?? 0) + 1 }));
253
+
254
+ // ** In a component: const [state, formAction] = useActionState(aSubscribe, null);
255
+ ```
256
+
257
+ ## Middleware and plugins
258
+
259
+ A middleware is an async function that calls `next()` and returns what it got back. Pass context forward with `next({ ctx })`; later steps see it, typed.
260
+
261
+ ```ts
262
+ import { actionCreate } from 'next-action-plus';
263
+
264
+ export const action = actionCreate()
265
+ .public()
266
+ .use(async props => {
267
+ const startedAt = Date.now();
268
+ const result = await props.next({ ctx: { requestId: crypto.randomUUID() } });
269
+ // ** result.ok, then result.data or result.error, and result.input (the input as the handler saw it)
270
+ console.info(props.meta, result.ok, Date.now() - startedAt);
271
+ return result;
272
+ });
273
+ ```
274
+
275
+ Rules the library enforces:
276
+
277
+ - A middleware must return the result of `next()`, otherwise the call fails. To stop a call, throw an error (`errorCreate` or a declared error).
278
+ - `next()` can be called once.
279
+ - `ctx` is frozen. Add to it with `next({ ctx })`; a later key with the same name wins, and the type follows.
280
+
281
+ ### Plugins
282
+
283
+ A plugin is a named middleware that can also declare error codes, and can act as the gate:
284
+
285
+ ```ts
286
+ import { errorCreate } from 'next-action-plus';
287
+ import type { TPlugin, TPluginShape } from 'next-action-plus/spec';
288
+
289
+ // ** A reusable plugin that needs ctx.user from an earlier gate
290
+ export const planRequire = (props: Readonly<{ plan: 'pro' | 'team' }>): TPlugin<TPluginShape<{ user: { plan: string } }>> => ({
291
+ name: 'plan-require',
292
+ version: 1,
293
+ run: async call => {
294
+ if (call.ctx.user.plan !== props.plan) throw errorCreate({ code: 'FORBIDDEN', message: `Upgrade to ${props.plan} to use this` });
295
+ return call.next();
296
+ },
297
+ });
298
+ ```
299
+
300
+ Because the plugin declares that it needs `ctx.user`, using it before a gate is a type error. Set `gate: true` on a plugin to make it count as the action's gate. `gateCreate` and every auth adapter do exactly that.
301
+
302
+ ### Recipe: an audit log for every admin action
303
+
304
+ ```ts
305
+ import { actionCreate } from 'next-action-plus';
306
+ import { gateCreate } from 'next-action-plus/gate';
307
+ import { redactValue } from 'next-action-plus/security/redact';
308
+
309
+ declare const adminFind: () => Promise<{ id: string; type: 'ADMINISTRATOR' } | null>;
310
+ declare const auditWrite: (row: object) => Promise<void>;
311
+
312
+ export const actionAdmin = actionCreate()
313
+ .use(gateCreate({ user: adminFind }))
314
+ .use(async props => {
315
+ const result = await props.next();
316
+ await auditWrite({ action: props.meta, admin: props.ctx.user.id, ok: result.ok, code: result.ok ? undefined : result.error.code, input: redactValue({ value: result.input }) });
317
+ return result;
318
+ });
319
+ ```
320
+
321
+ ## Responses: your own result shape
322
+
323
+ The library does not force a result shape on you. There are three modes.
324
+
325
+ **1. Raw (the default).** The handler's value is what the caller gets, and failures throw.
326
+
327
+ **2. A preset.**
328
+
329
+ | Preset | Success | Failure |
330
+ |---|---|---|
331
+ | `responseTuple()` | `[true, data]` | `[false, message, { code, issues, data, correlationId }]` |
332
+ | `responseResult()` | `{ ok: true, data }` | `{ ok: false, error: { code, message, issues, data, correlationId } }` |
333
+ | `responseProblem()` | `data` | RFC 9457 `{ type, title, status, detail, code, issues, data, correlationId }` |
334
+
335
+ **3. Your own contract.** Declare how a success and a failure look, plus how a client tells them apart. A type-lambda makes the result type follow each action's data and error codes:
336
+
337
+ ```ts
338
+ import { actionCreate, responseDefine, type TResponseLambda } from 'next-action-plus';
339
+
340
+ type TApiOut<Data, Error> = { status: 200; body: Data } | { status: number; code: Error extends { code: infer Code } ? Code : never; message: string };
341
+ interface TApi extends TResponseLambda {
342
+ readonly out: TApiOut<this['data'], this['error']>;
343
+ }
344
+
345
+ const response = responseDefine<TApi>({
346
+ success: props => ({ status: 200, body: props.data }),
347
+ failure: props => ({ status: props.error.status, code: props.error.code, message: props.error.message }),
348
+ ok: props => (props.result as { status: number }).status === 200,
349
+ });
350
+
351
+ export const action = actionCreate({ response }).public();
352
+ export const aPing = action.action(async () => 'pong'); // Promise<{ status: 200; body: string } | { status: number; code: ...; message: string }>
353
+ ```
354
+
355
+ Set a contract on the client with `actionCreate({ response })`, or on one action with `.response(...)`. Run `conformanceResponse` on your contract to check that results serialize and never leak an error's cause.
356
+
357
+ ## Errors
358
+
359
+ Every library error is a real `Error` with a `code`, a `status`, the `phase` it failed in, `issues` (for validation), `data`, a `correlationId`, and `expose` (whether the message is safe to show). Read one with `errorGet`:
360
+
361
+ ```ts
362
+ import { errorGet } from 'next-action-plus';
363
+
364
+ declare const aPostRename: (input: { id: string; title: string }) => Promise<unknown>;
365
+
366
+ try {
367
+ await aPostRename({ id: '1', title: '' });
368
+ } catch (error) {
369
+ const validation = errorGet({ error, code: 'VALIDATION' });
370
+ if (validation) console.log(validation.issues); // [{ path: ['title'], message: '...' }]
371
+ }
372
+ ```
373
+
374
+ ### Error codes
375
+
376
+ | Code | Status | When |
377
+ |---|---|---|
378
+ | `VALIDATION` | 400 | Input or bound args fail their schema. Message: `Input (path) is error: ...` |
379
+ | `UNAUTHORIZED` | 401 | A gate found no user |
380
+ | `FORBIDDEN` | 403 | A gate check, an authorize plugin, or the origin guard said no |
381
+ | `NOT_FOUND` | 404 | Yours to throw |
382
+ | `CONFLICT` | 409 | Idempotency: same key in flight (`IN_FLIGHT`) or reused with a different input (`KEY_REUSED`) |
383
+ | `RATE_LIMITED` | 429 | A rate limiter said no; `data.retryAfterMs` when known |
384
+ | `DROPPED` | 409 | Concurrency `drop`: a call was already running |
385
+ | `SUPERSEDED` | 409 | Concurrency `latest` / `keepLatest`: a newer call replaced this one |
386
+ | `LOCK_TIMEOUT` | 423 | Concurrency `queue`: still busy after `waitMs`, or the lock was lost |
387
+ | `TIMEOUT` | 504 | Concurrency `timeoutMs` passed |
388
+ | `ABORTED` | 499 | Reserved for cancelled calls |
389
+ | `LIMIT` | 413 | Input over a `limit`, or a prototype key |
390
+ | `STALE_ACTION` | 410 | Client side: the page is older than the deployed server (see [React](#react)) |
391
+ | `INTERNAL` | 500 | Anything unexpected. With a response contract the message is `Internal error`; the cause stays on the server |
392
+
393
+ Your own codes (from `.errors()` and plugins) default to status 400. Codes are part of your public API, so treat renaming one as a breaking change.
394
+
395
+ ### What the client sees
396
+
397
+ - **Raw mode:** your own thrown errors are rethrown unchanged (v1 behavior). In production builds, Next.js replaces thrown error messages with a digest, so the browser never sees them. Use a response contract when the client needs the message or code.
398
+ - **Response mode:** failures are returned as values. Unknown errors become `INTERNAL` with a `correlationId` you can find in your logs.
399
+ - **Navigation:** `redirect()`, `notFound()`, `forbidden()`, `unauthorized()` and dynamic-rendering bailouts always pass through untouched. They are never logged, wrapped or turned into a failure.
400
+
401
+ ### Messages and translations
402
+
403
+ `error.message` formats every exposed message (never `INTERNAL`). Use it for translations:
404
+
405
+ ```ts
406
+ import { getTranslations } from 'next-intl/server';
407
+ import { actionCreate } from 'next-action-plus';
408
+ import { i18nNextIntl } from 'next-action-plus/i18n/next-intl';
409
+
410
+ // ** messages: { "errors": { "RATE_LIMITED": "Wait {retryAfterMs}ms", "NOT_FOUND": "Not found" } }
411
+ export const action = actionCreate({ error: { message: i18nNextIntl({ translations: () => getTranslations('errors') }) } });
412
+ ```
413
+
414
+ Logging goes to `console.error` by default. Pass `log: yourLogger` or `log: false`. Input is never logged.
415
+
416
+ ## Security
417
+
418
+ Every Server Action can be called with a plain POST, even when no page renders it, and a page's auth check does not cover the actions in it. The library is built around that.
419
+
420
+ ### On by default
421
+
422
+ | Control | What it does |
423
+ |---|---|
424
+ | Gate required | `actionCreate()` refuses (type error and runtime error) an action without a gate plugin or `.public()` |
425
+ | Input limits | Max depth 32, 10,000 keys, 1,000,000-character strings, 10,000-item arrays, 10 MB files; own `__proto__` / `constructor` / `prototype` keys rejected. Tune with `limit: {...}` |
426
+ | Safe FormData | Prototype paths rejected, `$ACTION_*` fields skipped |
427
+ | Error masking | With a response contract, unknown errors become `INTERNAL` with a correlation id |
428
+ | Navigation passthrough | `redirect()` and friends never break |
429
+ | No input in logs | Failures are logged without the input |
430
+
431
+ ### Opt in
432
+
433
+ | Control | Import |
434
+ |---|---|
435
+ | Strict Origin and `Sec-Fetch-Site` check. Next.js skips its own check when a request has no Origin header | `security/origin` |
436
+ | Field stripping on results | `.output(schema)` |
437
+ | Validated bound args | `.args([...])` |
438
+ | Authorization after authentication | `authorize`, `authorize/*` |
439
+ | Rate limits (fail closed) | `rate/limit` |
440
+ | Idempotency keys | `idempotency` |
441
+ | Constant-time secret compare (API keys, webhook signatures) | `security/secret` |
442
+ | Safe log copies (masks secrets, strips CR/LF) | `security/redact` |
443
+
444
+ ```ts
445
+ import { headers } from 'next/headers';
446
+ import { actionCreate } from 'next-action-plus';
447
+ import { securityOrigin } from 'next-action-plus/security/origin';
448
+
449
+ export const action = actionCreate().use(securityOrigin({ allowed: ['app.acme.com', '*.acme-preview.com'], headers })).public();
450
+ ```
451
+
452
+ ### Checklist for B2B apps
453
+
454
+ 1. Put the gate on the client (`actionUser`, `actionAdmin`) so no action can forget it.
455
+ 2. Take the tenant from `ctx.user`, never from the input.
456
+ 3. Load records by id and tenant together, and answer `NOT_FOUND` rather than `FORBIDDEN`, so callers cannot probe which ids exist.
457
+ 4. Add `.output()` to anything that returns database rows.
458
+ 5. Give every `.bind()` value an `.args()` schema.
459
+ 6. Rate-limit by user and action name (`meta.name`).
460
+ 7. Add `securityOrigin` when you know your hosts.
461
+ 8. Do not rely on `middleware.ts` or `proxy.ts` for auth: it can be skipped (CVE-2025-29927). Gates run inside every action.
462
+ 9. Keep `react-server-dom-*` patched (CVE-2025-55182 and its follow-ups).
463
+ 10. Set `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` when you run more than one instance.
464
+
465
+ See [SECURITY.md](SECURITY.md) for the threat model and how to report a vulnerability.
466
+
467
+ ## Concurrency
468
+
469
+ `concurrencyCreate` decides what happens when the same key runs more than once at a time. The key is yours: a user, a document, a cart.
470
+
471
+ | Strategy | Meaning | Error for the losing call |
472
+ |---|---|---|
473
+ | `parallel` | Every call runs | — |
474
+ | `queue` | One at a time per key, in order | `LOCK_TIMEOUT` after `waitMs` |
475
+ | `drop` | Ignore calls while one runs | `DROPPED` |
476
+ | `latest` | A newer call aborts older ones through `ctx.concurrency.signal` | `SUPERSEDED` (when the old call checks the signal) |
477
+ | `keepLatest` | Finish the current call, then run only the newest waiting one | `SUPERSEDED` for the skipped ones |
478
+ | `dedupe` | Concurrent calls with the same key share one result (this instance only) | — |
479
+
480
+ ```ts
481
+ 'use server';
482
+
483
+ import { z } from 'zod';
484
+ import Redis from 'ioredis';
485
+ import { actionCreate } from 'next-action-plus';
486
+ import { concurrencyCreate } from 'next-action-plus/concurrency';
487
+ import { lockRedis } from 'next-action-plus/concurrency/lock/redis';
488
+
489
+ declare const db: { draftSave: (props: { id: string; body: string; version: number }) => Promise<boolean> };
490
+
491
+ const redis = new Redis(process.env.REDIS_URL as string);
492
+ const lock = lockRedis({ client: { eval: props => redis.eval(props.script, props.keys.length, ...props.keys, ...props.args) } });
493
+
494
+ export const aDraftSave = actionCreate()
495
+ .public()
496
+ .input(z.object({ id: z.string(), body: z.string() }))
497
+ .use(concurrencyCreate({ strategy: 'latest', key: props => `draft:${(props.input as { id: string }).id}`, lock, timeoutMs: 10_000 }))
498
+ .action(async props => {
499
+ const { signal, token } = props.ctx.concurrency;
500
+ signal.throwIfAborted();
501
+ // ** Fencing: the database ignores a write older than the newest token, so a stale call can never overwrite newer data
502
+ return db.draftSave({ id: props.input.id, body: props.input.body, version: token });
503
+ });
504
+ ```
505
+
506
+ What it can and cannot do:
507
+
508
+ - **A lock alone does not guarantee correctness.** Process pauses and clock jumps can let two holders overlap. That is why every run gets `ctx.concurrency.token`, a number that only goes up per key. Write it with your data and reject older writes, for example `UPDATE ... WHERE version < $token`.
509
+ - **Cancelling is cooperative.** A Server Action cannot be stopped from the browser, and React's docs say aborting does not undo server work. The `signal` fires on supersede, timeout or a lost lease. Pass it to `fetch` and to drivers that accept it, or check it between steps.
510
+ - **`latest` polls the lock's generation every `pollMs` (default 100ms)** while a call runs. That is one cheap read per running call.
511
+ - **The memory lock is correct for one server instance only.** Use `lockRedis` or `lockPostgres` (a lease table that also works behind PgBouncer) when you run more.
512
+ - **`dedupe` is for reads.** For writes, use `idempotencyCreate` with a key the client sends.
513
+
514
+ ## Adapters
515
+
516
+ Adapters take the vendor's client or function as a parameter. The library never imports the vendor SDK, so it adds nothing to your install and works with whatever version you use. "Experimental" means we built it from the vendor's published types and have not checked it against the live service yet.
517
+
518
+ ### Auth (gates)
519
+
520
+ | Adapter | Pass in | `ctx.user` |
521
+ |---|---|---|
522
+ | `auth/clerk` | `auth` from `@clerk/nextjs/server` | `{ id, auth }` |
523
+ | `auth/better-auth` | your `auth` and `headers` from `next/headers` | `{ id, user, session }` |
524
+ | `auth/authjs` | `auth` from your `auth.ts` | `{ id, session }` (id falls back to email) |
525
+ | `auth/supabase` | a function returning your server client (uses `getClaims()`) | `{ id, claims }` |
526
+ | `auth/kinde` | `getKindeServerSession` | `{ id, user, session }` |
527
+ | `auth/iron-session` | a function returning the session, and how to read the id | `{ id, session }` |
528
+ | `auth/workos` (experimental) | `withAuth` from `@workos-inc/authkit-nextjs` | `{ id, user, organizationId }` |
529
+
530
+ ```ts
531
+ import { auth } from '@clerk/nextjs/server';
532
+ import { actionCreate } from 'next-action-plus';
533
+ import { authClerk } from 'next-action-plus/auth/clerk';
534
+
535
+ export const actionUser = actionCreate().use(authClerk({ auth, check: props => props.user.auth.orgRole === 'org:admin' }));
536
+ ```
537
+
538
+ Your own auth works the same way through `gateCreate({ user, check })`.
539
+
540
+ ### Authorization
541
+
542
+ | Adapter | Calls |
543
+ |---|---|
544
+ | `authorize` | your `can(call)` |
545
+ | `authorize/cerbos` | `cerbos.isAllowed({ principal, resource, action })` |
546
+ | `authorize/permit` | `permit.check(user, action, resource)` |
547
+ | `authorize/casl` (experimental) | `ability.can(action, subject, field)` |
548
+ | `authorize/openfga` (experimental) | `client.check({ user, relation, object })` |
549
+ | `authorize/oso` (experimental) | `oso.authorize(actor, action, resource)` |
550
+
551
+ ### Rate limits
552
+
553
+ ```ts
554
+ import { Ratelimit } from '@upstash/ratelimit';
555
+ import { Redis } from '@upstash/redis';
556
+ import { after } from 'next/server';
557
+ import { actionCreate } from 'next-action-plus';
558
+ import { gateCreate } from 'next-action-plus/gate';
559
+ import { rateLimitCreate } from 'next-action-plus/rate/limit';
560
+ import { rateLimitUpstash } from 'next-action-plus/rate/limit/upstash';
561
+
562
+ declare const sessionUser: () => Promise<{ id: string } | null>;
563
+
564
+ const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, '10 s') });
565
+
566
+ export const actionUser = actionCreate()
567
+ .use(gateCreate({ user: sessionUser }))
568
+ .use(rateLimitCreate<{ user: { id: string } }>({ limiter: rateLimitUpstash({ ratelimit, wait: pending => after(pending) }), key: props => `${props.ctx.user.id}:${String((props.meta as { name?: string }).name)}` }));
569
+ ```
570
+
571
+ Also available: `rate/limit/arcjet` and `rate/limit/unkey` (experimental). A limiter that throws fails the call (`INTERNAL`); it never lets the call through.
572
+
573
+ ### Locks, key-value and idempotency
574
+
575
+ | Adapter | Client you pass |
576
+ |---|---|
577
+ | `concurrency/lock/memory`, `kv/memory` | nothing (one instance only) |
578
+ | `concurrency/lock/redis`, `kv/redis` | `{ eval: props => ... }`: one method, so ioredis, node-redis and `@upstash/redis` all fit |
579
+ | `concurrency/lock/postgres` | `{ query: props => pool.query(props.text, props.values) }` |
580
+
581
+ ```ts
582
+ import Redis from 'ioredis';
583
+ import { actionCreate } from 'next-action-plus';
584
+ import { idempotencyCreate } from 'next-action-plus/idempotency';
585
+ import { kvRedis } from 'next-action-plus/kv/redis';
586
+ import { z } from 'zod';
587
+
588
+ const redis = new Redis(process.env.REDIS_URL as string);
589
+ // ** @upstash/redis: { eval: props => upstash.eval(props.script, props.keys, props.args) }
590
+ const kv = kvRedis({ client: { eval: props => redis.eval(props.script, props.keys.length, ...props.keys, ...props.args) } });
591
+
592
+ export const aPaymentCreate = actionCreate()
593
+ .public()
594
+ .input(z.object({ idempotencyKey: z.string(), amount: z.number().positive() }))
595
+ .use(idempotencyCreate({ kv, key: props => (props.input as { idempotencyKey: string }).idempotencyKey }))
596
+ .action(async props => ({ charged: props.input.amount }));
597
+ ```
598
+
599
+ ### Queues
600
+
601
+ Every queue adapter has the same `enqueue({ name, payload, dedupe: { id }, delayMs })` method, so you can switch vendors without touching your actions: `queue/bullmq`, `queue/inngest`, `queue/qstash`, `queue/trigger`.
602
+
603
+ ```ts
604
+ import { Queue } from 'bullmq';
605
+ import { actionCreate } from 'next-action-plus';
606
+ import { queueBullmq } from 'next-action-plus/queue/bullmq';
607
+ import { z } from 'zod';
608
+
609
+ const emails = queueBullmq({ queue: new Queue('emails') });
610
+
611
+ export const aWelcomeSend = actionCreate()
612
+ .public()
613
+ .input(z.object({ userId: z.string() }))
614
+ .action(async props => emails.enqueue({ name: 'welcome', payload: props.input, dedupe: { id: `welcome:${props.input.userId}` } }));
615
+ ```
616
+
617
+ ### Telemetry
618
+
619
+ Next.js does not trace Server Actions by itself, and Sentry does not instrument them automatically.
620
+
621
+ | Adapter | What you get |
622
+ |---|---|
623
+ | `telemetry/otel` | A span per call, named `action <meta.name>`, with outcome, error code, correlation id and the recorded exception |
624
+ | `telemetry/sentry` | `withServerActionInstrumentation` around every call |
625
+ | `telemetry/pino` | One structured line per call: action, ok, durationMs, code, correlationId. Never the input |
626
+
627
+ ```ts
628
+ import { trace } from '@opentelemetry/api';
629
+ import { actionCreate } from 'next-action-plus';
630
+ import { telemetryOtel } from 'next-action-plus/telemetry/otel';
631
+
632
+ // ** Start the SDK in instrumentation.ts as usual; the library only uses @opentelemetry/api
633
+ export const action = actionCreate().use(telemetryOtel({ tracer: trace.getTracer('app') }));
634
+ ```
635
+
636
+ ## Writing your own adapter
637
+
638
+ Every contract lives in `next-action-plus/spec`. They are types only, and each one is versioned (`version: 1`), so a future change ships as a new interface and old adapters keep working.
639
+
640
+ | Contract | Methods |
641
+ |---|---|
642
+ | `TSchema` | Standard Schema v1 `~standard.validate` |
643
+ | `TPlugin` | `name`, `run(call)`, optional `gate`, `errors` |
644
+ | `TResponse` | `success`, `failure`, `ok` |
645
+ | `TLock` | `acquire({ key, leaseMs, waitMs })`, `generation({ key, bump })` |
646
+ | `TKv` | `get`, `set`, `add`, `delete` |
647
+ | `TRateLimiter` | `limit({ key, cost })` |
648
+ | `TQueue` | `enqueue({ name, payload, dedupe, delayMs })` |
649
+
650
+ ```ts
651
+ import type { TKv } from 'next-action-plus/spec';
652
+
653
+ declare const cache: { read: (key: string) => Promise<string | null>; write: (key: string, value: string, ttlMs?: number) => Promise<void>; writeIfAbsent: (key: string, value: string, ttlMs?: number) => Promise<boolean>; remove: (key: string) => Promise<void> };
654
+
655
+ export const kvMine = (): TKv => ({
656
+ name: 'mine',
657
+ version: 1,
658
+ get: async props => {
659
+ const raw = await cache.read(props.key);
660
+ return raw === null ? undefined : JSON.parse(raw);
661
+ },
662
+ set: props => cache.write(props.key, JSON.stringify(props.value), props.ttlMs),
663
+ add: props => cache.writeIfAbsent(props.key, JSON.stringify(props.value), props.ttlMs),
664
+ delete: props => cache.remove(props.key),
665
+ });
666
+ ```
667
+
668
+ Then prove it follows the contract with the same suite our adapters pass:
669
+
670
+ ```ts
671
+ // kv-mine.test.ts
672
+ import { describe } from 'vitest';
673
+ import { conformanceKv } from 'next-action-plus/conformance';
674
+ import type { TKv } from 'next-action-plus/spec';
675
+
676
+ declare const kvMine: () => TKv;
677
+
678
+ describe('my kv', () => conformanceKv({ kv: () => kvMine() }));
679
+ ```
680
+
681
+ Suites: `conformanceLock`, `conformanceKv`, `conformanceResponse`, `conformancePlugin`.
682
+
683
+ ## React
684
+
685
+ `useAction` calls a server action from a Client Component and gives you `status`, `result`, `error`, callbacks, optimistic state and a client-side strategy:
686
+
687
+ ```tsx
688
+ 'use client';
689
+
690
+ import { useAction } from 'next-action-plus/react';
691
+
692
+ declare const aDraftSave: (input: { id: string; body: string }) => Promise<boolean>;
693
+
694
+ export const ViewDraftEditor = (props: Readonly<{ id: string }>) => {
695
+ const { id } = props;
696
+ const save = useAction({ action: aDraftSave, strategy: 'latest', debounceMs: 400, onError: error => console.error(error) });
697
+
698
+ return (
699
+ <div>
700
+ <textarea onChange={event => void save.execute({ id, body: event.target.value })} />
701
+ <span>{save.status === 'pending' ? 'Saving…' : save.status === 'error' ? 'Not saved' : 'Saved'}</span>
702
+ </div>
703
+ );
704
+ };
705
+ ```
706
+
707
+ | Option | Meaning |
708
+ |---|---|
709
+ | `strategy` | `parallel` (default), `queue`, `drop`, `latest`, `keepLatest`, the same meanings as on the server but for this component |
710
+ | `debounceMs` | Send only the last call after a quiet period |
711
+ | `ok` | With a response contract, pass its `ok` so failures returned as values count as errors |
712
+ | `optimistic` | `{ state, update }`: shows the update while the call runs and rolls back when it ends (React's `useOptimistic`) |
713
+ | `onSuccess`, `onError`, `onSettled` | Callbacks |
714
+
715
+ - `execute` does not throw on failure. It resolves the result, or `undefined` when the call was dropped, superseded, debounced away or failed. The one exception is Next.js navigation (`redirect()`, `notFound()`): those errors are rethrown so the router can act on them.
716
+ - It runs inside a transition, so `revalidatePath` and `redirect()` work as usual.
717
+ - After a deploy, old tabs call action ids the server no longer has. `useAction` turns that into an error with code `STALE_ACTION`, so you can ask the user to reload.
718
+
719
+ ## Testing your actions
720
+
721
+ Actions are plain async functions, so you test them by calling them. Keep request access (headers, cookies) inside your gate's `user` function, and tests can swap it:
722
+
723
+ ```ts
724
+ import { describe, expect, it } from 'vitest';
725
+ import { z } from 'zod';
726
+ import { actionCreate, errorGet } from 'next-action-plus';
727
+ import { gateCreate } from 'next-action-plus/gate';
728
+
729
+ const actionAs = (user: { id: string } | null) => actionCreate({ log: false }).use(gateCreate({ user: () => user }));
730
+ const rename = (user: { id: string } | null) => actionAs(user).input(z.object({ title: z.string().min(1) })).action(async props => ({ title: props.input.title, by: props.ctx.user.id }));
731
+
732
+ describe('rename', () => {
733
+ it('renames for a signed-in user', async () => {
734
+ await expect(rename({ id: 'u1' })({ title: 'New' })).resolves.toEqual({ title: 'New', by: 'u1' });
735
+ });
736
+
737
+ it('refuses anonymous callers', async () => {
738
+ const error = await rename(null)({ title: 'New' }).catch(caught => caught);
739
+ expect(errorGet({ error, code: 'UNAUTHORIZED' })).toBeDefined();
740
+ });
741
+ });
742
+ ```
743
+
744
+ ## TypeScript tips
745
+
746
+ - **Let inference work.** Do not annotate handler parameters; `props` is typed from the chain.
747
+ - **Use helper types for your own response shape.** TypeScript allows `this['data']` only at the top of `out`, so put the shape in a helper type (see [Responses](#responses-your-own-result-shape)).
748
+ - **Read types from an action** with `Awaited<ReturnType<typeof aX>>` and `Parameters<typeof aX>`.
749
+ - **Editor speed.** 40 actions with gates, plugins, error maps and deep schemas check in about 0.25s (63k type instantiations). CI fails if that grows past budget.
750
+ - **`state.previous` in `.actionState` is `unknown`.** It is whatever the browser last held, so narrow it before use.
751
+
752
+ ## FAQ
753
+
754
+ ### What is next-action-plus?
755
+
756
+ next-action-plus is a TypeScript library that wraps Next.js Server Actions with input validation, auth gates, middleware, typed errors and an optional response shape, while keeping each action a plain async function.
757
+
758
+ ### Which validators does it support?
759
+
760
+ Any validator that implements Standard Schema v1: Zod 3.24+ and 4, Valibot 1, ArkType 2, Effect Schema, Yup, or a hand-written object with a `~standard` property. The library does not depend on any of them.
761
+
762
+ ### Do I still need zod-form-data?
763
+
764
+ No. FormData is decoded into a plain object before validation, so a normal object schema works. Use `z.coerce.number()` (or your validator's coercion) for number fields, because form values arrive as strings.
765
+
766
+ ### Why does my action without auth not compile?
767
+
768
+ `actionCreate()` requires a gate by default, because every Server Action is a public endpoint. Add an auth adapter or `gateCreate(...)`, call `.public()` for truly open actions, or create the client with `gate: { required: false }` to turn the rule off.
769
+
770
+ ### Does it work with `useActionState` and forms without JavaScript?
771
+
772
+ Yes. Pass an action to `<form action>`, and it works before hydration. For `useActionState`, build it with `.actionState(...)`, which takes `(previousState, input)`.
773
+
774
+ ### How is it different from next-safe-action?
775
+
776
+ Both validate input and run middleware. next-action-plus adds a required gate by default, lets you define the result shape (or keep the raw value), types every error code, and ships concurrency control, idempotency and adapters behind small contracts you can replace.
777
+
778
+ ### Can a Server Action be cancelled?
779
+
780
+ Not from the browser: a sent call runs to the end on the server. next-action-plus gives handlers a `signal` that fires when a newer call supersedes it, a timeout passes or a lock is lost, plus a fencing token so a stale call cannot overwrite newer data.
781
+
782
+ ### Does it run on the Edge runtime?
783
+
784
+ Yes. The core and most adapters use only Web APIs (`crypto.randomUUID`, `crypto.subtle`). Adapters whose drivers need Node.js (Postgres, BullMQ) run on Node.js only.
785
+
786
+ ## Migrating from v1
787
+
788
+ ### Renames
789
+
790
+ | v1 | v2 |
791
+ |---|---|
792
+ | `createActionPlus(options)` | `actionCreate(options)` |
793
+ | `.schema(s)` | `.input(s)` (once per action) |
794
+ | `({ parsedInput })` | `({ input })` |
795
+ | `logger: false` | `log: false` |
796
+ | `onError`, `formatError`, `formatValidationError` | A middleware that reads `next()`'s result, or a response contract |
797
+ | `includeInputInErrorDetails` | Removed (the input is never attached) |
798
+ | `ActionPlusError`, `ActionPlusValidationError`, `isActionPlusError`, `isActionPlusValidationError` | `errorGet({ error, code })`, `TError` |
799
+ | `TMiddlewareFn`, `TInfer`, `TInferIn`, `TStandardSchemaV1` | `TMiddleware`, `TSchemaOutput`, `TSchemaInput`, `TSchema` |
800
+ | Generic `{ parse }` schemas | Standard Schema validators (Zod 3.24+ already is one) |
801
+ | Several chained `.schema()` calls, merged | One `.input()`; validate slices in a middleware |
802
+ | `zod-form-data` | Not needed: FormData is decoded for you |
803
+
804
+ ### Run the codemod
805
+
806
+ Run it **before** upgrading, while v1 is still installed, because it follows your types to change only what comes from next-action-plus.
807
+
808
+ ```bash
809
+ npx next-action-plus@2 codemod v2 .
810
+ ```
811
+
812
+ ```bash
813
+ npx next-action-plus@2 codemod v2 . --write
814
+ ```
815
+
816
+ ```bash
817
+ npm i next-action-plus@2
818
+ ```
819
+
820
+ The first command is a dry run that prints every change. The codemod:
821
+
822
+ - renames `createActionPlus` to `actionCreate`, and writes `{ gate: { required: false }, limit: false }` into each client, so behavior stays exactly as in v1 (no required gate, no input limits);
823
+ - renames `.schema(` to `.input(` and `parsedInput` to `input` in handlers. A shorthand `{ parsedInput }` that you pass on becomes `{ parsedInput: input }`, so your own APIs keep their keys;
824
+ - when a handler already declares a local `input`, it writes `{ input: parsedInput }` and notes it;
825
+ - adds a `TODO(next-action-plus v2)` comment wherever it cannot rewrite safely: removed exports, v1-only options, options passed as a variable, and code that patches the v1 class prototype.
826
+
827
+ ### By hand
828
+
829
+ - **Prototype patches.** v2 has no class. Replace `Object.getPrototypeOf(client).action = ...` with a middleware on the client; `next()` returns `{ ok, data | error, input }`, which is what an audit hook needs.
830
+ - **Middleware placed before `.schema()`.** In v1 every middleware saw the parsed input. In v2 a middleware sees the parsed input only when it comes after `.input()`. Inside a middleware, `(await props.next()).input` is always the parsed input.
831
+ - **Turn on the v2 defaults when you are ready.** Remove `gate: { required: false }` to require a gate on every action, and `limit: false` to enable input limits.
832
+
833
+ ### New type errors you may see
834
+
835
+ Both point to real bugs that v1 hid:
836
+
837
+ - **"Expected 1 arguments, but got 0"**: the input schema requires a value, so calling the action without one fails validation at runtime. Pass the input, or make the schema optional.
838
+ - **A union or boolean input that was `never`**: v1 turned `z.union`, `z.discriminatedUnion` and `z.boolean()` into `never`. In v2 they are typed correctly, which can expose code that relied on the wrong type.
839
+
840
+ ### Before and after
841
+
842
+ ```ts
843
+ // ** v1
844
+ // export const aNotificationRead = actionClient.schema(z.object({ ids: z.array(z.string()).optional() })).action(async ({ parsedInput }) => { ... parsedInput.ids ... });
845
+
846
+ // ** v2
847
+ import { z } from 'zod';
848
+ import { actionCreate } from 'next-action-plus';
849
+
850
+ const actionClient = actionCreate({ gate: { required: false }, limit: false });
851
+
852
+ export const aNotificationRead = actionClient.input(z.object({ ids: z.array(z.string()).optional() })).action(async ({ input }): Promise<[true] | [false, string]> => {
853
+ if (input.ids?.length === 0) return [false, 'Nothing to read'];
854
+ return [true];
855
+ });
856
+ ```
857
+
858
+ Your handlers keep returning your own tuples. Nothing about the return value changes.
859
+
860
+ ## License
861
+
862
+ MIT