javascript / expert
Snippet
Functional Middleware for Secure Server Actions
Higher-order functions can act as middleware for React Server Actions. This pattern centralizes security concerns like authentication and logging, ensuring they are consistently applied without cluttering individual action logic.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type Action<T> = (formData: FormData) => Promise<T>;function withAuth<T>(action: Action<T>): Action<T> {return async (formData: FormData) => {const session = await getSession();if (!session) throw new Error("Unauthorized");// Log action for security auditingconsole.log(`User ${session.userId} performing action`);return action(formData);};}// Usage in a component or server fileconst deletePost = withAuth(async (formData) => {'use server';await db.posts.delete(formData.get('id'));});
react
Breakdown
1
function withAuth<T>(action: Action<T>): Action<T>
A wrapper that takes an action and returns a new version with injected security logic.
2
if (!session) throw new Error("Unauthorized");
Enforces authorization at the function boundary before the core logic executes.
3
return action(formData);
Delegates execution to the original action once all checks have passed.