javascript
53 lines · 9 steps
Role-based permissions middleware in Express
A middleware factory turns a static role-to-permission map into per-route access control.
Explained by
highlit
1const ROLE_PERMISSIONS = {
2 admin: ['users:read', 'users:write', 'billing:read', 'billing:write'],
3 manager: ['users:read', 'billing:read'],
4 member: ['users:read'],
5};
6
7function hasPermission(role, permission) {
8 const granted = ROLE_PERMISSIONS[role] || [];
9 return granted.includes(permission);
10}
11
12function requirePermission(...required) {
13 return (req, res, next) => {
14 if (!req.user) {
15 return res.status(401).json({ error: 'Authentication required' });
16 }
17
18 const missing = required.filter(
19 (permission) => !hasPermission(req.user.role, permission)
20 );
21
22 if (missing.length > 0) {
23 return res.status(403).json({
24 error: 'Insufficient permissions',
25 required: missing,
26 });
27 }
28
29 next();
30 };
31}
32
33const router = require('express').Router();
34
35router.get(
36 '/users',
37 requirePermission('users:read'),
38 usersController.list
39);
40
41router.post(
42 '/users',
43 requirePermission('users:write'),
44 usersController.create
45);
46
47router.patch(
48 '/billing/:id',
49 requirePermission('billing:read', 'billing:write'),
50 billingController.update
51);
52
53module.exports = { router, requirePermission };
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A middleware factory lets you configure per-route behavior by returning a closure over its arguments.
- 2Centralizing permissions in one map keeps authorization logic declarative and easy to audit.
- 3Distinguishing 401 from 403 correctly separates 'not logged in' from 'not allowed'.
Related explainers
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/role-based-permissions-middleware-in-express-explained-javascript-b01f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.