javascript / expert
Snippet
Fine-Grained Authorization with Bitwise Operators
Bitwise operators allow for extremely memory-efficient storage and fast checking of multiple boolean flags (permissions) within a single integer. This is an expert pattern for high-performance authorization systems.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Permissions = {READ: 1 << 0, // 0001WRITE: 1 << 1, // 0010DELETE: 1 << 2, // 0100ADMIN: 1 << 3 // 1000};const userPerms = Permissions.READ | Permissions.WRITE;const canWrite = (userPerms & Permissions.WRITE) !== 0;const canDelete = (userPerms & Permissions.DELETE) !== 0;// Next.js Metadata / Access Checkif (!(userPerms & Permissions.ADMIN)) {// Restricted access}
nextjs
Breakdown
1
1 << 0, 1 << 1...
Uses the left-shift operator to create unique power-of-two values for each permission flag.
2
userPerms = Permissions.READ | Permissions.WRITE;
Combines multiple permissions into a single bitmask using the bitwise OR operator.
3
(userPerms & Permissions.WRITE) !== 0
Checks for a specific permission using the bitwise AND operator to isolate the relevant bit.