Guide

Send contact form submissions to Discord or Slack with a Cloudflare Worker

27 November 2026 · About a 12-minute read

Email is the default place for contact form messages, but it isn’t always where you look. If your team already lives in a Discord server or a Slack workspace, a new enquiry in a channel gets seen in minutes instead of sitting under a newsletter. Both apps give you an incoming webhook: a secret URL that turns one JSON POST into a channel message. No bot, no OAuth flow, no mail provider, no domain verification.

This guide wires a static site’s contact form to either or both, using a Cloudflare Pages Function (or a standalone Worker) on the free plan. It covers creating each webhook, storing the URL as a secret, a complete handler with validation and a honeypot, payloads that can’t ping @everyone, the length limits that cause silent 400s, and what to check when nothing shows up.

Why a webhook instead of email

  • Nothing to verify. Sending email from a Worker means a provider account, a verified domain, and SPF/DKIM records. A webhook is one URL.
  • Shared by default. Everyone in the channel sees the message, can react to it, and can start a thread on who’s replying.
  • Easy to debug. Either the message is in the channel or the API returned an error you can log.

The trade-offs are real, too. You can’t reply to a chat message and reach the visitor, so always include their email address in the post. The message now lives on Discord’s or Slack’s servers, which is worth a line in your privacy notice. And a webhook is not storage: if the post fails and you didn’t save the submission anywhere else, it’s gone. Treat the webhook as the alert, not the archive. For anything that matters, store first and notify second, as described in Send email from a Worker contact form.

Step 1: Create a Discord webhook

You need the Manage Webhooks permission on the server (server owners and admins have it).

  1. Open Server Settings → Integrations → Webhooks. You can also start from a channel’s Edit Channel → Integrations.
  2. Click New Webhook, give it a name such as “Contact form”, and pick the channel it should post to.
  3. Click Copy Webhook URL. It looks like https://discord.com/api/webhooks/<id>/<token>.

The token at the end of the URL is the credential. Anyone who has the full URL can post to that channel, so don’t paste it into a chat, a commit, or your front-end code.

Step 2: Create a Slack incoming webhook

Slack webhooks belong to a Slack app. The app takes a minute to create and doesn’t need any code.

  1. Go to api.slack.com/apps, choose Create New App → From scratch, name it, and select your workspace.
  2. In the app’s settings, open Incoming Webhooks and switch the feature on.
  3. Add a new webhook, choose the channel, and approve the install. Some workspaces require an admin to approve new apps first.
  4. Copy the URL. It starts with https://hooks.slack.com/services/.

Each Slack webhook URL is tied to one channel. The channel can’t be changed in the payload, so create one webhook per channel you want to post to.

Step 3: Store the URL as a secret

The webhook URL must only exist on the server side. Store it as an encrypted secret, not as a plain variable in wrangler.toml and never in your HTML or JavaScript bundle.

# Standalone Worker
npx wrangler secret put DISCORD_WEBHOOK_URL
npx wrangler secret put SLACK_WEBHOOK_URL

# Pages project (Pages Function)
npx wrangler pages secret put DISCORD_WEBHOOK_URL --project-name=my-site
npx wrangler pages secret put SLACK_WEBHOOK_URL --project-name=my-site

Wrangler prompts for the value, so it doesn’t end up in your shell history. In the dashboard, the same setting is under your Worker or Pages project’s Settings → Variables and Secrets; choose the secret type so the value is hidden after you save it. Pages applies new variables to the next deployment, so redeploy (or retry the latest deployment) after adding them.

For local development, put the values in a .dev.vars file next to your wrangler.toml (or project root). Both wrangler dev and wrangler pages dev read it.

# .dev.vars (local only; add it to .gitignore)
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...

Before writing any handler code, check the URL works on its own. This rules out the most common problem, a URL that was copied incompletely or belongs to a deleted webhook:

# Discord: expect HTTP 204 and a message in the channel
curl -i -H "Content-Type: application/json" \
  -d '{"content":"Webhook test","allowed_mentions":{"parse":[]}}' \
  "$DISCORD_WEBHOOK_URL"

# Slack: expect HTTP 200 and the body "ok"
curl -i -H "Content-Type: application/json" \
  -d '{"text":"Webhook test"}' \
  "$SLACK_WEBHOOK_URL"

Step 4: The form

A plain HTML form is enough. It posts to /api/contact on the same domain, so there’s no CORS to configure, and it works with JavaScript turned off.

<form method="post" action="/api/contact">
  <div class="hp" aria-hidden="true">
    <label>Website <input name="website" tabindex="-1" autocomplete="off"></label>
  </div>
  <label>Name <input name="name" required maxlength="100" autocomplete="name"></label>
  <label>Email <input name="email" type="email" required maxlength="254" autocomplete="email"></label>
  <label>Message <textarea name="message" required minlength="10" maxlength="5000"></textarea></label>
  <button type="submit">Send</button>
</form>

<style>
  .hp { position: absolute; left: -10000px; }
</style>

The website field is a honeypot. It’s pushed off-screen with CSS rather than hidden with type="hidden", because many bots fill every field that looks visible. tabindex="-1" keeps keyboard users out of it. The browser checks (required, maxlength) are for convenience only; the server repeats all of them.

Step 5: The handler

Save this as functions/api/contact.js in your Pages project. Cloudflare serves it at /api/contact, and because the export is onRequestPost, only POST requests reach it. It’s plain JavaScript, so it needs no build step; rename it to .ts and add types if you prefer TypeScript.

// functions/api/contact.js  →  POST /api/contact on Cloudflare Pages

const MAX = { name: 100, email: 254, message: 5000 };
const DISCORD_CONTENT_MAX = 2000; // Discord rejects longer message content
const SLACK_TEXT_MAX = 3000;      // limit for a section block's text
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Cut a string to `max` characters, ending with "…" if it was longer.
function clip(s, max) {
  if (s.length <= max) return s;
  let cut = s.slice(0, max - 1);
  if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1); // don't split an emoji
  return cut + "…";
}

function validate(fields) {
  const values = {
    name: String(fields.name ?? "").replace(/\s+/g, " ").trim(),
    email: String(fields.email ?? "").trim(),
    message: String(fields.message ?? "").replace(/\r\n/g, "\n").trim(),
  };
  const errors = {};
  if (!values.name) errors.name = "Please enter your name.";
  else if (values.name.length > MAX.name) errors.name = "That name is too long.";
  if (!EMAIL_RE.test(values.email) || values.email.length > MAX.email) {
    errors.email = "Please enter a valid email address.";
  }
  if (values.message.length < 10) errors.message = "Please write a little more.";
  else if (values.message.length > MAX.message) errors.message = "Please keep it under 5,000 characters.";
  return { values, errors };
}

function buildDiscordPayload(v, page) {
  const header = [
    "**New contact form message**",
    `From: ${v.name} (${v.email})`,
    `Page: ${page}`,
    "",
  ].join("\n");
  return {
    username: "Contact form",
    content: header + clip(v.message, DISCORD_CONTENT_MAX - header.length),
    allowed_mentions: { parse: [] }, // never ping @everyone, @here, users or roles
    flags: 4,                        // SUPPRESS_EMBEDS: no link previews for pasted URLs
  };
}

// Slack mrkdwn treats &, < and > as control characters (<!channel>, <@U123>, <url|text>).
function slackEscape(s) {
  return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}

function slackText(s, max) {
  const escaped = slackEscape(s);
  if (escaped.length <= max) return escaped;
  return clip(escaped, max).replace(/&[a-z]*…$/, "…"); // don't leave half an &amp;
}

function buildSlackPayload(v, page) {
  return {
    // `text` is the fallback shown in notifications and on clients without blocks
    text: slackText(`New contact form message from ${v.name}`, 300),
    blocks: [
      { type: "header", text: { type: "plain_text", text: "New contact form message" } },
      {
        type: "section",
        fields: [
          { type: "mrkdwn", text: `*Name*\n${slackText(v.name, 200)}` },
          { type: "mrkdwn", text: `*Email*\n${slackText(v.email, 300)}` },
        ],
      },
      { type: "section", text: { type: "mrkdwn", text: slackText(v.message, SLACK_TEXT_MAX) } },
      { type: "context", elements: [{ type: "mrkdwn", text: `Sent from ${slackText(page, 500)}` }] },
    ],
  };
}

async function postWebhook(label, url, payload) {
  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
    signal: AbortSignal.timeout(8000),
  });
  if (!res.ok) {
    // Log the status and the reason, never the URL: the URL is the credential.
    const detail = (await res.text()).slice(0, 300);
    throw new Error(`${label} webhook failed: ${res.status} ${detail}`);
  }
}

function reply(wantsJson, status, errors) {
  if (wantsJson) {
    return Response.json({ ok: status < 300, errors: errors ?? {} }, { status });
  }
  if (status < 300) {
    return new Response(null, { status: 303, headers: { Location: "/thanks/" } });
  }
  const text = Object.values(errors ?? {}).join("\n") || "Something went wrong.";
  return new Response(text + "\n\nPlease go back and try again.", {
    status,
    headers: { "Content-Type": "text/plain; charset=utf-8" },
  });
}

async function handleContact(request, env) {
  const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json");

  let fields;
  try {
    const form = await request.formData();
    fields = Object.fromEntries(
      [...form.entries()].filter(([, value]) => typeof value === "string"),
    );
  } catch {
    return reply(wantsJson, 400, { form: "We couldn't read that form." });
  }

  // Honeypot: real people never see this field. Pretend it worked.
  if (String(fields.website ?? "").trim() !== "") return reply(wantsJson, 200);

  const { values, errors } = validate(fields);
  if (Object.keys(errors).length > 0) return reply(wantsJson, 422, errors);

  const page = clip(request.headers.get("Referer") ?? "unknown page", 300);
  const jobs = [];
  if (env.DISCORD_WEBHOOK_URL) {
    jobs.push(postWebhook("Discord", env.DISCORD_WEBHOOK_URL, buildDiscordPayload(values, page)));
  }
  if (env.SLACK_WEBHOOK_URL) {
    jobs.push(postWebhook("Slack", env.SLACK_WEBHOOK_URL, buildSlackPayload(values, page)));
  }
  if (jobs.length === 0) {
    console.error("No DISCORD_WEBHOOK_URL or SLACK_WEBHOOK_URL is set");
    return reply(wantsJson, 500, { form: "The form isn't set up yet. Please email us instead." });
  }

  const results = await Promise.allSettled(jobs);
  const failed = results.filter((r) => r.status === "rejected");
  for (const r of failed) console.error(r.reason?.message ?? r.reason);

  // Nothing is stored in this version, so only report success if a message got through.
  if (failed.length === jobs.length) {
    return reply(wantsJson, 502, {
      form: "Your message couldn't be delivered. Please try again in a minute, or email us.",
    });
  }
  return reply(wantsJson, 200);
}

export const onRequestPost = ({ request, env }) => handleContact(request, env);

What each part is doing

  • Validation on the server. Names are collapsed to one line (so a name can’t inject extra lines into the Discord header), the email gets a basic shape check, and the message has a minimum and maximum length. Only string fields are read, so an uploaded file is ignored rather than stringified.
  • The honeypot returns the normal success response and sends nothing. Telling a bot it was caught only helps it adapt.
  • allowed_mentions: { parse: [] } tells Discord not to turn any text in the message into a ping. Without it, a visitor who types @everyone or @here can notify the whole server, and a pasted user or role mention pings that person or role. With it, the text still shows but nobody is pinged.
  • flags: 4 is Discord’s SUPPRESS_EMBEDS flag. Spam often contains links, and this stops Discord from unfurling a preview for each one.
  • Slack escaping. In Slack’s mrkdwn, mentions and links use angle brackets: <!channel>, <@U123>, <https://…|label>. Escaping &, < and > as Slack’s documentation asks turns all of those into plain text. The header block uses plain_text, which isn’t parsed at all.
  • A text fallback with blocks. When you send blocks, Slack uses text for the notification preview and for clients that can’t render blocks, so always include it.
  • Length limits before sending. The Discord message is cut to 2,000 characters and the Slack section to 3,000, with an ellipsis, so a long message is shortened instead of rejected. clip also avoids cutting an emoji in half, and slackText avoids leaving half of an &amp; entity at the end.
  • Non-2xx responses are errors. fetch only throws on network failures, so the handler checks res.ok and logs the status and the first part of the response body. It never logs the URL, because the URL is the secret.
  • A timeout. AbortSignal.timeout(8000) means a slow webhook can’t keep the visitor waiting indefinitely.
  • Honest responses. This version doesn’t store anything, so it only reports success if at least one webhook accepted the message. If both fail, the visitor gets a 502 and a request to try again or email you, instead of a “thanks” for a message nobody will see.

Add a page at /thanks/ for the no-JavaScript redirect. If you submit with fetch and an Accept: application/json header, the handler replies with {"ok": true} or the field errors instead. The Astro guide has a small progressive-enhancement script that works with this response shape.

The same code as a standalone Worker

If your site isn’t on Cloudflare Pages, or several sites share one endpoint, run the handler as its own Worker. Everything above stays the same except the last line:

// src/index.js: the same handler as a standalone Worker
// (paste clip, validate, the payload builders, postWebhook, reply and handleContact above this)

export default {
  async fetch(request, env) {
    const { pathname } = new URL(request.url);
    if (pathname === "/api/contact" && request.method === "POST") {
      return handleContact(request, env);
    }
    return new Response("Not found", { status: 404 });
  },
};

Deploy it with npx wrangler deploy and set the secrets with npx wrangler secret put. On a different origin from your site, the browser’s fetch needs CORS headers, and the no-JS redirect should point back to an absolute URL on your site. The Hugo, Astro, and Eleventy guide covers both.

A standalone Worker is also where storing first becomes easy: insert the row into D1, return the redirect, and post to Discord or Slack inside ctx.waitUntil() so the visitor never waits on a webhook. The Turnstile tutorial builds that D1 inbox.

Limits worth knowing

PlatformLimitWhat happens if you exceed it
DiscordMessage content up to 2,000 characters400 error; nothing is posted
DiscordEmbeds: description up to 4,096 characters, all embeds in a message 6,000 combined400 error
SlackSection block text up to 3,000 characters; header text up to 150; up to 50 blocks per message400 invalid_blocks or similar
SlackTop-level text: keep it short; very long messages are truncatedTruncated, not rejected
BothPer-webhook rate limits429 Too Many Requests

Slack documents roughly one message per second per webhook, with short bursts allowed. Discord returns a 429 with a retry_after value when you post too fast. A contact form rarely gets near either, unless it’s being flooded, which is one more reason to rate-limit the form itself.

Security notes

  • Never call the webhook from the browser. It’s tempting to fetch the Discord URL straight from the page and skip the Worker. Anyone can then read the URL in the page source and post whatever they like to your channel, as often as they like. The whole point of the Worker is that the URL stays on the server.
  • If a URL leaks, replace it. Delete the webhook in Discord’s Integrations settings, or remove it from the Slack app’s Incoming Webhooks page, create a new one, and update the secret. Deleting is the only way to invalidate it.
  • Spam lands in a channel people watch. A honeypot stops the laziest bots, not all of them. Add Cloudflare Turnstile for a challenge that is invisible to most visitors, and see Stop contact form spam without a CAPTCHA for a time trap, link rules, and per-IP rate limiting with KV or the Workers rate limiting binding.
  • Treat the content as untrusted. Discord renders Markdown in webhook messages, including masked links, so a message can show link text that doesn’t match where it goes. Don’t click links in submissions without checking them.
  • Send only what you need. Don’t forward IP addresses or other metadata to a chat app just because it’s available. Name, email, message and the page are usually enough.

Test it locally

With .dev.vars in place, run the project with Wrangler and submit from curl. The message below deliberately includes @everyone and <!channel>; it should appear as plain text, with no pings.

npx wrangler pages dev ./public    # or your build output folder

# in another terminal
curl -i http://localhost:8788/api/contact \
  -H "Accept: application/json" \
  -F name="Test Person" -F email="test@example.com" \
  -F message="Testing the Discord and Slack notifications. @everyone <!channel>"

Then try the failure paths: an invalid email (422 with errors), a filled-in website field (200 and nothing posted), and a deliberately broken webhook URL in .dev.vars (502, with the status logged in the terminal).

Troubleshooting

  • Nothing arrives and the logs say “No DISCORD_WEBHOOK_URL or SLACK_WEBHOOK_URL is set”. The secret is missing in this environment. Secrets set for Production don’t apply to Preview deployments, Pages needs a redeploy after a change, and wrangler dev reads .dev.vars, not your dashboard values.
  • Discord 401 or 404 (“Unknown Webhook”). The webhook was deleted or the URL is incomplete. Copy it again from Integrations.
  • Discord 400. Usually an empty or over-long content, or a malformed field. The response body names the field; it’s in your log because the handler records the first 300 characters.
  • Slack 400 invalid_payload or invalid_blocks. The JSON isn’t valid or a block breaks a rule (too long, wrong type). Paste the payload into Slack’s Block Kit Builder to see which block is the problem.
  • Slack 403, 404 or 410. The app was uninstalled or the webhook revoked, the channel was deleted, or the channel is archived. Create a new webhook.
  • 429 Too Many Requests. You’re posting faster than the webhook allows, which usually means a bot found the form. Add rate limiting rather than retries.
  • The form says success but nothing appears. Check the honeypot field isn’t being filled by browser autofill or a password manager; keep autocomplete="off" on it and give it a name that isn’t a real field like email.
  • A GET to /api/contact returns 404. That’s expected. The function only exports onRequestPost.
  • Mentions still ping. Check that allowed_mentions is spelled exactly and sits at the top level of the Discord payload, not inside an embed.

If you’d rather not maintain it

The code above is complete for a single contact form that alerts a channel. Formharbor is the larger version, built as a standalone Worker. Discord and Slack are built in: set DISCORD_WEBHOOK_URL and/or SLACK_WEBHOOK_URL with wrangler secret put, and after each accepted submission is saved to D1, the Worker posts a plain-text summary (form name, submission ID and the submitted fields) in the background. If a post fails, the error is logged and the submission is still in your /admin dashboard. Its posts are plain text; it doesn’t use the embed or block layouts shown here, and the payload builders above can be dropped into its src/notify.ts if you want them. The kit also includes Turnstile verification, a honeypot and timing trap, per-IP rate limits, optional Resend email, CSV export, a referral waitlist, and R2 file uploads. It costs $19 once and runs on your own Cloudflare free tier.

More guides

Want this already built?

Formharbor is a $19 one-time kit: contact forms, referral waitlists, and file uploads on your Cloudflare free tier.

Get Formharbor