javascript / expert
Snippet
Proxy-Based Dynamic Branch Evaluation for Reactive Navigation Guards in Next.js App Router
This pattern uses JavaScript Proxy objects to dynamically intercept control flow evaluation in Next.js Middleware. Instead of pre-building nested conditional branches or static maps, property getters dynamically resolve permission checks (e.g. guard.canAccessAdmin) by trap evaluation, creating lightweight and dynamic authorization guards.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export function createPermissionGuard(userRoles) {return new Proxy({}, {get(target, prop) {if (typeof prop !== 'string') return false;const requiredRole = prop.toLowerCase().replace(/^canaccess/, '');return userRoles.includes(requiredRole);}});}export async function middleware(req) {const roles = req.headers.get('x-user-roles')?.split(',') || [];const guard = createPermissionGuard(roles);if (!guard.canAccessAdmin && req.nextUrl.pathname.startsWith('/admin')) {return NextResponse.redirect(new URL('/unauthorized', req.url));}return NextResponse.next();}
nextjs
Breakdown
1
return new Proxy({}, {
Instantiates an Object Proxy with a trap handler to wrap arbitrary property reads.
2
get(target, prop) {
Intercepts dynamic property lookups on the proxy instance.
3
if (!guard.canAccessAdmin && req.nextUrl.pathname.startsWith('/admin')) {
Evaluates dynamic permission branch to route flow conditionally.