| name | safe-action-middleware |
| description | Use when implementing middleware for next-safe-action -- authentication, authorization, logging, rate limiting, error interception, context extension, or creating standalone reusable middleware with createMiddleware() |
next-safe-action Middleware
Quick Start
import { createSafeActionClient } from "next-safe-action";
const actionClient = createSafeActionClient();
const authClient = actionClient.use(async ({ next }) => {
const session = await getSession();
if (!session?.user) {
throw new Error("Unauthorized");
}
return next({
ctx: { userId: session.user.id },
});
});
How Middleware Works
.use() adds middleware to the chain — you can call it multiple times
- Each
.use() returns a new client instance (immutable chain)
- Middleware executes top-to-bottom (in the order added)
- Results flow bottom-to-top (the deepest middleware/action resolves first)
- Context is accumulated via
next({ ctx }) — each level's ctx is deep-merged with the previous
const client = createSafeActionClient()
.use(async ({ next }) => {
console.log("1: before");
const result = await next({ ctx: { a: 1 } });
console.log("1: after");
return result;
})
.use(async ({ next, ctx }) => {
console.log("2: before", ctx.a);
const result = await next({ ctx: { b: 2 } });
console.log("2: after");
return result;
});
Middleware Function Signature
async ({
clientInput,
bindArgsClientInputs,
ctx,
metadata,
next,
}) => {
return next({
ctx: {
},
});
};
Supporting Docs
Anti-Patterns
.use(async ({ next }) => {
await doSomething();
next({ ctx: {} });
})
.use(async ({ next }) => {
await doSomething();
return next({ ctx: {} });
})
.use(async ({ next }) => {
try {
return await next({ ctx: {} });
} catch (error) {
return { serverError: "Something went wrong" };
}
})
.use(async ({ next }) => {
try {
return await next({ ctx: {} });
} catch (error) {
if (error instanceof Error && "digest" in error) {
throw error;
}
console.error(error);
return { serverError: "Something went wrong" };
}
})