0 day streak
javascript / expert
Snippet

Dynamic Logic Injection via Higher-Order Server Actions

In Next.js, Higher-Order Functions can wrap Server Actions to inject cross-cutting concerns like logging, validation, or telemetry without polluting the core business logic. This functional approach promotes reusability and clean separation of concerns.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type Action<T, R> = (data: T) => Promise<R>;
function withLogging<T, R>(action: Action<T, R>): Action<T, R> {
return async (data: T) => {
console.log(`Executing with data:`, data);
const result = await action(data);
console.log(`Finished execution.`);
return result;
};
}
const secureAction = withLogging(async (payload: { id: string }) => {
return { success: true };
});
nextjs
Breakdown
1
return async (data: T) => {
Returns a new asynchronous function that wraps the original action.
2
const result = await action(data);
Calls the original business logic within the decorated wrapper.
3
const secureAction = withLogging(...);
Creates a decorated version of the action ready for use in components.