T
TanStack3d ago
metropolitan-bronze

Throw `json` in middleware not working for route rendered on server

I have a basic role check in server middleware. In the loaderData function of a Route, it makes a call to a server function using that middleware. However, the server crashes when the route attempts to be loaded by a server without the required role. Any reason why this would be? My middleware:
export const requireRoleMiddleware = (requiredRole: User['role']) =>
createMiddleware({ type: 'function' })
.middleware([userRequiredMiddleware])
.server(async ({ next, context }) => {
const userRole = context.userSession!.user.role;

if (roleHierarchy.indexOf(requiredRole) < roleHierarchy.indexOf(userRole)) {
throw json({ error: 'Forbidden' }, { status: 403 });
}
return next({ context: { userSession: context.userSession } });
});
export const requireRoleMiddleware = (requiredRole: User['role']) =>
createMiddleware({ type: 'function' })
.middleware([userRequiredMiddleware])
.server(async ({ next, context }) => {
const userRole = context.userSession!.user.role;

if (roleHierarchy.indexOf(requiredRole) < roleHierarchy.indexOf(userRole)) {
throw json({ error: 'Forbidden' }, { status: 403 });
}
return next({ context: { userSession: context.userSession } });
});
1 Reply
passive-yellow
passive-yellow3d ago
"crashes" how? probably best if you can provide a complete minimal example repository

Did you find this page helpful?