Stop form spam in SvelteKit
Updated
This guide adds Bot403 to a contact form in SvelteKit 3. The browser solves a small proof of work, and a form action checks the token with one call to https://bot403.com/api/v1/verify before it accepts the message. The free plan covers 5,000 checks a month. It works with use:enhance, and with no JavaScript in the page the form still submits. The traps are new in SvelteKit 3: the secret key goes through src/env.js, $lib is now #lib, and vite build checks your environment variables.
The example uses @sveltejs/kit 3.2.0, svelte 5.57.3, vite 8.3.8, @sveltejs/adapter-node 6.0.2 and @bot403/node 1.0.2. We built it and sent forms to it on 12 November 2026, against a local stand-in for the verify API (see "Test it").
Before you start
Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Put the secret key in an environment variable, never in your code or your repository.
npm install @bot403/node
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEYThe files you add or change:
package.json # "imports" for #lib
src/app.html # the script tag
src/env.js # declares BOT403_SECRET_KEY
src/lib/server/bot403.js # the client
src/routes/contact/+page.svelte
src/routes/contact/+page.server.js
src/routes/thanks/+page.svelte1. The script tag
Put the script tag in src/app.html, before %sveltekit.head%. It then loads once and protects every form in the app, also forms that appear after a client-side navigation. Before the browser sends a form, the script adds a hidden _bot403 field with the token, and a hidden honeypot field.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" defer></script>
%sveltekit.head%
</head>
<body>
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>If you set csp in the SvelteKit config, allow https://bot403.com in script-src and in connect-src. The script fetches its challenge from there.
2. The secret key and the client
SvelteKit 3 reads environment variables that src/env.js declares. Server code imports them from $app/env/private:
import { defineEnvVars } from '@sveltejs/kit/env';
export const variables = defineEnvVars({
BOT403_SECRET_KEY: { description: 'The secret key (sk_live_…) of the Bot403 site' }
});The client lives in src/lib/server, so SvelteKit never sends it to the browser. It gets a 5-second timeout here. The default is 10 seconds.
import { Bot403 } from '@bot403/node';
import { BOT403_SECRET_KEY } from '$app/env/private';
export const bot403 = new Bot403({ secretKey: BOT403_SECRET_KEY, timeoutMs: 5000 });SvelteKit 3 also removed the $lib alias. Use #lib, a subpath import that package.json declares:
{
"imports": {
"#lib/*": "./src/lib/*"
}
}3. The form
A plain <form method="POST"> posts to the default action of the page. use:enhance sends it without a full page reload when JavaScript runs.
<script>
import { enhance } from '$app/forms';
let { form } = $props();
</script>
<form method="POST" use:enhance>
<label>Email <input name="email" type="email" value={form?.email ?? ''} required /></label>
<label>Message <textarea name="message" required></textarea></label>
{#if form?.failed}<p>The form check failed. Please send it again.</p>{/if}
<button type="submit">Send</button>
</form><p>Thanks. Your message is on its way.</p>4. The action
The action sends the whole form to Bot403. verifyForm() posts it to the verify API with your secret key. The action accepts the message only when the answer is ok. If Bot403 does not answer, the action accepts the form and logs a warning. A wrong secret key or too many verify calls a minute throw an error, so you see them and fix them.
import { Bot403Error } from '@bot403/node';
import { fail, redirect } from '@sveltejs/kit';
import { bot403 } from '#lib/server/bot403.js';
async function bot403Check(data) {
try {
// 1. Post the whole form: Bot403 reads the _bot403 field and the honeypot field.
const result = await bot403.verifyForm(data);
// 2. Refuse when ok is false, except for reason "quota"
return result.ok || result.reason === 'quota';
} catch (e) {
if (!(e instanceof Bot403Error) || e.status !== 0) throw e; // 401 wrong key, 429 too many calls
console.warn('bot403 did not answer, letting the form through:', e.message);
return true;
}
}
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
if (!(await bot403Check(data))) {
return fail(400, { email: data.get('email'), failed: true });
}
// A real visitor: send the email or store the message here
redirect(303, '/thanks');
}
};A failed token is a normal answer, not an exception: result.ok is false and result.reason says why. The verify page lists every reason. fail(400, …) sends the email address back, so the visitor does not type it again.
redirect() throws. Keep it outside any try block. The SvelteKit docs warn: "Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it."
The trap: env checks and #lib in SvelteKit 3
Guides written for SvelteKit 2 use $env/static/private and $lib. In SvelteKit 3 the $env modules are deprecated, and the $lib alias is gone. With $lib, the build stops with: "$lib has been removed. Use #lib instead".
vite build also checks every variable in src/env.js. If BOT403_SECRET_KEY is not set while you build, the build stops with "Invalid environment variables" and "Value is missing". So set the variable in your build step too. The value is not written into the build: in our test, the server used the key from its own environment when it started, and the key from the build was in no output file.
If the variable is set but empty, new Bot403() throws "secretKey is required" when the server starts. Both errors show up before any visitor sends a form.
Does it work with use:enhance?
Yes. use:enhance sends the form with fetch, and the token goes with it. The Bot403 script listens for the submit event on the form in the capture phase, which runs before the bubble-phase listener of use:enhance. If the token is not ready, the script holds the submit, puts the token in the _bot403 field and submits again. Then use:enhance sends the form, and the action gets the token.
After a successful submit, use:enhance resets the form. The next submit gets a new token, because each token works only once.
The origin check
In production, SvelteKit refuses a form POST whose Origin header is not the site's own origin. It answers 403 with "Cross-site POST form submissions are forbidden". The check does not run with vite dev. This has two effects:
- A test with curl needs an
Originheader, as in "Test it". Without it, you get the 403 from SvelteKit, not an answer from Bot403. - If every real form gets this 403, the server does not know its own public origin. With adapter-node, set
ORIGINto the public URL of the site.
Keep the check on. It stops other sites that send forms in the name of your visitor. Bot403 does not do that job. It stops scripts that send forms automatically.
Test it
Build the app and start it. Then send forms with curl. vite build needs the variable, as described above.
BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY npm run build
PORT=3000 ORIGIN=http://localhost:3000 BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY node buildA form without a token must be refused with 400:
curl -s -o /dev/null -w '%{http_code}\n' -H 'Origin: http://localhost:3000' -H 'Accept: text/html' \
--data 'email=a%40example.com&message=hi' http://localhost:3000/contact
# 400Then open http://localhost:3000/contact in a browser and send the form. The browser goes to /thanks, and the site in your dashboard shows one check.
This is what we got on 12 November 2026, with the verify API replaced by a local stand-in that gave fixed answers:
| What was sent | Answer from the app |
|---|---|
| A good token | 303 to /thanks |
A used token (replay) |
400, form shown again with the email filled in |
No token (invalid) |
400 |
A capped month (quota, HTTP 402) |
the form goes through |
| Verify API not reachable | the form goes through, with a warning in the log |
No Origin header |
403 "Cross-site POST form submissions are forbidden" |
use:enhance request, good token |
{"type":"redirect","status":303,"location":"/thanks"} |
use:enhance request, used token |
{"type":"failure","status":400, …} |
Troubleshooting
- Every form gets a 400. Log
result.reasoninbot403Check. If it isinvalid, the form arrives without a_bot403field. Check that the script tag is insrc/app.htmland that the public key is right. In the browser's developer tools, the form data of the POST must hold_bot403. - The build stops with "Invalid environment variables". Set
BOT403_SECRET_KEYin the build step. - 403 "Cross-site POST form submissions are forbidden". See "The origin check".
- Your own end-to-end tests with Playwright get
automation. That is on purpose. Use a separate test site with Automated browsers set to Off.
The troubleshooting page lists every reason and its fix, and the JavaScript packages page documents @bot403/node. For other JavaScript frameworks, read Stop form spam in Next.js and Stop form spam in Astro. All guides are on the guides page. For Vue, read Stop form spam in Nuxt.
Stop spam, not customers.
The CAPTCHA your visitors never see.