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:
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.
1Verify Slack v0 Signature & 5-Minute Replay Window in Route Handler
src/app/api/webhooks/slack/route.tsRead 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.tstypescriptimport 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')}!`, }); }2Store SLACK_SIGNING_SECRET Strictly Server-Side in .env
.env.localCopy the Signing Secret (not the legacy deprecated Verification Token) from Slack App -> Basic Information -> App Credentials.
.env.localdotenvSLACK_SIGNING_SECRET="replace_with_slack_app_signing_secret" SLACK_BOT_TOKEN="xoxb-replace-with-bot-token"3Avoid Duplicate Bot Replies on Slack Automatic Retries
src/app/api/webhooks/slack/route.tsIf 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.tstypescriptif (request.headers.get('x-slack-retry-num')) { return NextResponse.json({ ok: true, skipped: 'retry' }); }4Reply Asynchronously Using response_url for Heavy Slash Commands
src/lib/slackReply.tsRespond 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.tstypescriptexport 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.
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.
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.
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.
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:
Audit Next.js App Router .env.local and .env.production files in your browser. Catch NEXT_PUBLIC_ secret leaks, build-time inlining bugs, and missing keys.
Generate a production Nginx reverse proxy for Next.js App Router on port 3000 with Certbot SSL, _next/static caching, streaming responses, and WebSockets.
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.
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →Stripe Webhook Verification in Next.js App Router (request.text() Guide)
Fix Stripe webhook signature mismatch in Next.js App Router Route Handlers. Use await request.text() instead of request.json() with timingSafeEqual.
GitHub Webhook X-Hub-Signature-256 Verification in Node.js Express
Verify GitHub X-Hub-Signature-256 HMAC-SHA256 webhooks in Express.js using raw Buffers, sha256= prefix validation, and crypto.timingSafeEqual.
Stripe Webhook Verification in Node.js Express (express.raw() Order Fix)
Fix Stripe webhook signature mismatch in Express.js. Mount express.raw({ type: "application/json" }) before express.json() and verify with timingSafeEqual.
ASP.NET Core 8/9 Raw Body Webhook HMAC Verification (EnableBuffering Guide)
Verify Stripe, GitHub, and Shopify HMAC-SHA256 webhooks in ASP.NET Core 8/9 using EnableBuffering(), StreamReader, and FixedTimeEquals in C#.