Webhook HMAC-SHA256 Verifier · Slack + Next.js

Slack Slash Command & Events Signature Verification in Next.js App Router

Verify and generate Slack + Next.js HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·X-Slack-Signature

X-Slack-Signature: v0=a54abdea6831539015cd1b684aeeb3428433097acf21265bd919bc922c4818ce

X-Slack-Request-Timestamp: 1795378346

// src/app/api/webhooks/slack/route.ts (Next.js App Router — Node.js Runtime)
import crypto from 'node:crypto';
import { NextResponse } from 'next/server';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  // CRITICAL: Read raw text BEFORE parsing JSON so whitespace & key order stay intact
  const rawBody = await request.text();
  const secret = process.env.WEBHOOK_SECRET!;

  const timestamp = request.headers.get('x-slack-request-timestamp') ?? '';
  const received = request.headers.get('x-slack-signature') ?? '';

  if (!timestamp || Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) {
    return NextResponse.json({ error: 'Replay timestamp rejected' }, { status: 400 });
  }

  const expected = 'v0=' + crypto.createHmac('sha256', secret).update(`v0:${timestamp}:${rawBody}`).digest('hex');

  const expectedBuf = Buffer.from(expected, 'utf8');
  const receivedBuf = Buffer.from(received, 'utf8');

  if (expectedBuf.length !== receivedBuf.length || !crypto.timingSafeEqual(expectedBuf, receivedBuf)) {
    return NextResponse.json({ error: 'Invalid Slack signature' }, { status: 400 });
  }

  const event = JSON.parse(rawBody);
  return NextResponse.json({ received: true, type: event.type ?? 'ok' });
}
1. Raw Body HMAC (HEX)Valid

a54abdea6831539015cd1b684aeeb3428433097acf21265bd919bc922c4818ce

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

06b27a3f0ba42c553ba07159b7a6f8bcf7a02f4a65e45ea489dc2687f977c7c4

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (Slack + Next.js)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in Slack + Next.js, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

401 Unauthorized: Invalid X-Slack-Signature — computed HMAC over rawBody without "v0:{timestamp}:" prefix or parsed form-urlencoded body before signing.

Raw Request Stream Handling & Replay Protection in Slack + Next.js

Slack Apps; covering both Events API JSON callbacks and Slash Command application/x-www-form-urlencoded payloads; authenticate every outbound request using a versioned HMAC-SHA256 signature. Slack builds the signing base string by concatenating "v0:" + X-Slack-Request-Timestamp + ":" + rawBody, hashes it with your Slack App Signing Secret, and sends "v0=<hex>" inside the X-Slack-Signature header.

In Next.js App Router Route Handlers, verifying Slack signatures fails for two recurring reasons. First, for Slash Commands (which arrive as form-urlencoded strings like "token=..&command=%2Fdeploy&text=prod"), calling await request.formData() and rebuilding URLSearchParams alters percent-encoding (e.g., spaces as %20 vs +) and breaks HMAC verification completely. Always call const rawBody = await request.text() first, verify the signature over rawBody, and ONLY THEN parse new URLSearchParams(rawBody) or JSON.parse(rawBody).

Second, Slack requires strict 5-minute (300-second) replay protection on X-Slack-Request-Timestamp AND enforces a hard 3-second response deadline. If your Next.js Route Handler performs slow AI inference or database queries before replying, Slack displays "dispatch_failed" or "operation_timeout" inside the user's channel and retries the exact same event up to 3 times.

Checking the X-Slack-Retry-Num header (or deduplicating on event_id) prevents duplicate bot replies, while acknowledging Slack within milliseconds and using waitUntil() or an async queue keeps Slash Commands snappy and reliable.

Use the browser Web Crypto debugger above to generate valid Slack v0 signatures with live Unix timestamps and copy the exact timing-safe Next.js App Router Route Handler.

Production Slack bots built on Next.js App Router should treat every incoming slash command and event callback as untrusted until both X-Slack-Request-Timestamp (within 300 seconds) and v0 HMAC verification succeed over await request.text(). Offloading slow database or AI operations to background jobs and posting delayed responses back to Slack's response_url prevents cold-start timeouts and eliminates duplicate retry messages in busy team channels.

Step-by-Step Slack + Next.js Webhook Verification Setup

Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.

  1. 1Verify Slack v0 Signature & 5-Minute Replay Window in Route Handler

    src/app/api/webhooks/slack/route.ts

    Read rawBody via await request.text(), validate X-Slack-Request-Timestamp within 300 seconds, compare v0=<hex> with crypto.timingSafeEqual(), and handle Slack's url_verification challenge cleanly.

    src/app/api/webhooks/slack/route.tstypescript
    import crypto from 'node:crypto';
    import { NextResponse } from 'next/server';
    
    export const runtime = 'nodejs';
    export const dynamic = 'force-dynamic';
    
    export async function POST(request: Request) {
      const rawBody = await request.text();
      const timestamp = request.headers.get('x-slack-request-timestamp') ?? '';
      const signature = request.headers.get('x-slack-signature') ?? '';
      const secret = process.env.SLACK_SIGNING_SECRET!;
    
      const now = Math.floor(Date.now() / 1000);
      if (!timestamp || Math.abs(now - Number(timestamp)) > 300) {
        return NextResponse.json({ error: 'Stale Slack timestamp' }, { status: 400 });
      }
    
      const baseString = `v0:${timestamp}:${rawBody}`;
      const expected =
        'v0=' + crypto.createHmac('sha256', secret).update(baseString, 'utf8').digest('hex');
    
      const a = Buffer.from(expected, 'utf8');
      const b = Buffer.from(signature, 'utf8');
    
      if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
        return NextResponse.json({ error: 'Invalid Slack signature' }, { status: 401 });
      }
    
      // Handle Events API JSON or Slash Command form-urlencoded AFTER verification
      const contentType = request.headers.get('content-type') ?? '';
      if (contentType.includes('application/json')) {
        const body = JSON.parse(rawBody);
        if (body.type === 'url_verification') {
          return NextResponse.json({ challenge: body.challenge });
        }
        return NextResponse.json({ ok: true });
      }
    
      const params = new URLSearchParams(rawBody);
      return NextResponse.json({
        response_type: 'ephemeral',
        text: `Received command ${params.get('command')}!`,
      });
    }
  2. 2Store SLACK_SIGNING_SECRET Strictly Server-Side in .env

    .env.local

    Copy the Signing Secret (not the legacy deprecated Verification Token) from Slack App -> Basic Information -> App Credentials.

    .env.localdotenv
    SLACK_SIGNING_SECRET="replace_with_slack_app_signing_secret"
    SLACK_BOT_TOKEN="xoxb-replace-with-bot-token"
  3. 3Avoid Duplicate Bot Replies on Slack Automatic Retries

    src/app/api/webhooks/slack/route.ts

    If your serverless function experienced a cold start > 3 seconds, Slack resends the event with X-Slack-Retry-Num. Return 200 immediately or deduplicate using event_id.

    src/app/api/webhooks/slack/route.tstypescript
    if (request.headers.get('x-slack-retry-num')) {
      return NextResponse.json({ ok: true, skipped: 'retry' });
    }
  4. 4Reply Asynchronously Using response_url for Heavy Slash Commands

    src/lib/slackReply.ts

    Respond to Slack within 3 seconds with an immediate acknowledgment, then POST the final rich Block Kit payload to the command's response_url from a background worker.

    src/lib/slackReply.tstypescript
    export async function postDelayedSlackReply(responseUrl: string, text: string) {
      await fetch(responseUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ response_type: 'in_channel', text }),
      });
    }

Common Slack + Next.js Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Using await request.formData() on Slack Slash Commands Before Hashing

Slash commands arrive as application/x-www-form-urlencoded. Reading request.formData() consumes the body and loses the exact percent-encoding Slack signed. Always call await request.text() first.

Pitfall 2

Forgetting the "v0:" Prefix in BOTH the Base String and Header

Slack prepends "v0:" to the signing base ("v0:{timestamp}:{rawBody}") AND prepends "v0=" to X-Slack-Signature. Missing either version prefix causes immediate 401 failures.

Pitfall 3

Exceeding Slack's Strict 3-Second Response Timeout

Even when HMAC verification succeeds, taking 3.5 seconds to query an LLM or database causes Slack to abort with "operation_timeout" and trigger duplicate retries.

Related Tools

Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers

Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:

Frequently Asked Questions

Does Slack still use the legacy Verification Token?
No. Slack deprecated Verification Tokens in favor of the HMAC-SHA256 Signing Secret (X-Slack-Signature + X-Slack-Request-Timestamp). Always use Signing Secret verification for new Slack apps.
Does Slack sign the initial url_verification challenge request too?
Yes. Slack signs the url_verification challenge with your Signing Secret just like regular events, so verifying X-Slack-Signature before echoing { challenge } is completely safe and recommended.
Why does my Slack timestamp check fail locally when replaying a captured curl request?
Captured requests older than 300 seconds fail the replay-attack tolerance check. Click "Set Now (Unix)" in the Web Crypto debugger above to generate a fresh valid timestamp and v0 signature for local testing.
Should I verify Slack signatures in Next.js middleware.ts or route.ts?
Verify inside route.ts (pinned to runtime = "nodejs") so you can read await request.text() directly without cloning request streams across Edge middleware boundaries.
Browse all 10 webhook guides →