Templates / Webhooks

Slack slash command backend with signature verification

Handle a Slack slash command (/status, /lookup …): verify Slack’s request signature, parse the form body and reply in the channel within 3 seconds.

Slash commands post a form to your URL and expect an answer within three seconds. This function verifies the request really comes from Slack, reads the command and replies visibly in the channel.

Build it with Wisp

Type this into Wisp, or press Build this — it writes the code below, deploys it and gives you a URL:

A POST endpoint for a Slack slash command that verifies X-Slack-Signature with SLACK_SIGNING_SECRET, reads the command text from the form body and replies in the channel.

The code

POST /slack-command · API

import { createHmac, timingSafeEqual } from 'node:crypto';
import { config } from 'wisp';

export async function handler(req) {
  const raw = Buffer.from(req.rawBody ?? '', req.isBase64Encoded ? 'base64' : 'utf8').toString('utf8');
  const ts = req.headers['x-slack-request-timestamp'] ?? '';
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return { status: 401, body: 'Stale request' };
  const expected = 'v0=' + createHmac('sha256', config.require('SLACK_SIGNING_SECRET')).update(`v0:${ts}:${raw}`).digest('hex');
  const given = req.headers['x-slack-signature'] ?? '';
  if (given.length !== expected.length || !timingSafeEqual(Buffer.from(given), Buffer.from(expected))) {
    return { status: 401, body: 'Invalid signature' };
  }

  const form = Object.fromEntries(new URLSearchParams(raw));
  const text = (form.text ?? '').trim();
  const reply = text ? `<@${form.user_id}> asked about *${text}* — here's what I found: …` : 'Usage: /lookup <order id>';
  return { body: { response_type: text ? 'in_channel' : 'ephemeral', text: reply } };
}

Set it up

Add these in the project’s Variables & secrets (secrets are encrypted and never shown in logs):

Try it

In your Slack app: Slash Commands → Create New Command, set the Request URL to your function’s URL, install the app, then type the command in any channel.

How it works

Variations

Questions

Why does Slack say “operation_timeout”? Your reply took more than 3 seconds. Answer immediately, then send the real result to the response_url from the request.

Build it with Wisp — free trial

Related