withUserPermissions
Purpose:
withUserPermissions is a reusable API wrapper for Next.js/Node.js route handlers. It automatically augments any JSON response with the current user's permissions, making it easy for frontend code to know what permissions the user hasโwithout extra API calls.
Usageโ
import { withUserPermissions } from './withUserPermissions';
async function getHandler(req, ctx) {
// ...your handler logic...
return NextResponse.json({ foo: 'bar' });
}
export default withUserPermissions(getHandler);
You can also compose it with other wrappers:
export default withUserRoles(withUserPermissions(getHandler));
APIโ
- Input: An async handler
(req, ctx) => NextResponse - Output: A handler that returns the same response, but with a
userPermissionsarray in the JSON (if available) - If the user is not authenticated:
userPermissionswill beundefined - If the handler returns non-JSON: The response is returned as-is
Example Responseโ
{
"foo": "bar",
"userPermissions": ["read", "write"]
}
Caveatsโ
- If the user is not logged in,
userPermissionswill not be present. - If the handler returns a non-JSON response, it will not be modified.
- If fetching permissions fails, the response will still be returned (with
userPermissions: undefined). - This wrapper is fully composable with other wrappers (like
withUserRoles).
When to Useโ
- Any API where the frontend needs to know the user's permissions for UI/logic.
- To avoid extra round-trips for permission/role checks.
- For scalable, DRY, and maintainable API design.
For more details, see the source code and tests in this directory.