withUserRoles
Purpose:
withUserRoles is a reusable API wrapper for Next.js/Node.js route handlers. It automatically augments any JSON response with the current user's roles, making it easy for frontend code to know what roles the user hasโwithout extra API calls.
Usageโ
import { withUserRoles } from './withUserRoles';
async function getHandler(req, ctx) {
// ...your handler logic...
return NextResponse.json({ foo: 'bar' });
}
export default withUserRoles(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
userRolesarray in the JSON (if available) - If the user is not authenticated:
userRoleswill beundefined - If the handler returns non-JSON: The response is returned as-is
Example Responseโ
{
"foo": "bar",
"userRoles": ["admin", "wizard"]
}
Caveatsโ
- If the user is not logged in,
userRoleswill not be present. - If the handler returns a non-JSON response, it will not be modified.
- If fetching roles fails, the response will still be returned (with
userRoles: undefined). - This wrapper is fully composable with other wrappers (like
withUserPermissions).
When to Useโ
- Any API where the frontend needs to know the user's roles 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.