DEV Community

Jason Y. (dev_in_the_fog)
Jason Y. (dev_in_the_fog)

Posted on Originally published at global-utils.com

Fixing Next.js Edge Middleware node:crypto Crashes (Web Crypto API + Audit CLI)

Every developer hits this error on their first Edge Middleware deployment: code that works flawlessly in next dev suddenly crashes at build or deploy time with:

Module not found: Can't resolve 'node:crypto' in Edge Runtime
ReferenceError: Buffer is not defined
Enter fullscreen mode Exit fullscreen mode

Next.js Middleware and Edge Route Handlers run in a V8 isolate (WinterCG-compatible Edge Runtime), not Node.js. Core Node built-ins (node:crypto, node:fs, crypto.randomBytes, and global Buffer) are unavailable.

Here is the exact migration map from Node crypto / Buffer to standard Web Crypto API (globalThis.crypto), plus a zero-dependency pre-deploy CLI scanner.


1. The 4 Patterns That Break in Edge Runtime

Node.js Pattern (Fails in Edge) Web Crypto / Edge Replacement
import crypto from 'node:crypto' Use globalThis.crypto.subtle directly (no import)
crypto.createHash('sha256').update(str).digest('hex') await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str))
crypto.createHmac('sha256', key).update(msg).digest() crypto.subtle.importKey('raw', ..., { name: 'HMAC', hash: 'SHA-256' }, ...) + crypto.subtle.sign
Buffer.from(str, 'base64url') / crypto.randomBytes(32) Uint8Array + crypto.getRandomValues(new Uint8Array(32))

2. Production Drop-In Replacement (HMAC-SHA256 + Timing-Safe Compare)

A common mistake when migrating crypto.timingSafeEqual to the Edge is comparing strings with ===, which reintroduces timing side-channels. Here is a portable Web Crypto implementation:

const encoder = new TextEncoder();

export async function signEdgeToken(payload: string, secret: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  );

  const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(payload));
  return btoa(String.fromCharCode(...new Uint8Array(signature)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.byteLength !== b.byteLength) return false;
  let diff = 0;
  for (let i = 0; i < a.byteLength; i++) {
    diff |= a[i] ^ b[i];
  }
  return diff === 0;
}
Enter fullscreen mode Exit fullscreen mode

And remember: btoa() throws on non-Latin1 bytes if you pass raw UTF-8 strings directly. Always encode to Uint8Array via TextEncoder before converting bytes.


3. Automated Pre-Deploy Scan (edge-crypto-check)

I published a tiny zero-dependency CLI (JangYS0/edge-crypto-check) that flags node:crypto, crypto.randomBytes, Buffer.from/alloc, and node:fs across middleware.ts and Edge files in CI:

git clone https://github.com/JangYS0/edge-crypto-check
node edge-crypto-check/bin/cli.mjs ./src/middleware.ts
Enter fullscreen mode Exit fullscreen mode

4. Full Walkthrough & Free Browser Debuggers

Top comments (0)