javascript / expert
Snippet
HMAC Signature Verification via Web Crypto API in Next.js Route Handlers
Verifying webhook authenticity in Next.js Edge or Node.js Route Handlers requires low-level Web Crypto API primitives. Importing a raw cryptographic key into crypto.subtle and running constant-time signature verification prevents timing attacks on webhook endpoints.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { NextResponse } from 'next/server';export async function POST(request) {const secret = process.env.WEBHOOK_SECRET;const signature = request.headers.get('x-signature');const rawBody = await request.arrayBuffer();const key = await crypto.subtle.importKey('raw',new TextEncoder().encode(secret),{ name: 'HMAC', hash: 'SHA-256' },false,['verify']);const sigBuffer = Uint8Array.from(Buffer.from(signature || '', 'hex'));const isValid = await crypto.subtle.verify('HMAC', key, sigBuffer, rawBody);if (!isValid) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });return NextResponse.json({ success: true });}
nextjs
Breakdown
1
const rawBody = await request.arrayBuffer();
Reads the incoming request stream directly as an ArrayBuffer to preserve exact byte sequence for cryptographic evaluation.
2
const key = await crypto.subtle.importKey(
Imports the raw string secret into a Web Crypto CryptoKey instance configured specifically for HMAC-SHA256 verification.
3
const isValid = await crypto.subtle.verify('HMAC', key, sigBuffer, rawBody);
Executes hardware-accelerated, timing-safe HMAC signature verification comparing the signature against raw payload bytes.