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
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
python
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent
How a Django settings module is wired
configuration
environment-variables
middleware
Intermediate
8 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.