Next.js CAPTCHA: Solve It in a Route Handler (Node.js SDK)

To solve a Next.js CAPTCHA from server code, call CapSkip inside an App Router Route Handler that runs on the Node.js runtime, then return the token or use it in the same request. This guide is for a developer whose Next.js server must pass a CAPTCHA on a page it doesn’t own, not for adding one to your own site. The handler asks the capskip 1.7.0 package for a Cloudflare Turnstile token, keeps its secrets on the server and sets a timeout that fits the function limit. Each task goes to the CapSkip Turnstile solver, which runs on a Windows PC you own and charges nothing per solve.
What you need
- A Windows PC with CapSkip running. Local mode listens on 127.0.0.1, port 8080 by default. Install steps are in the setup guide.
- Node.js 20.9 or later, the floor in the engines field of Next.js 16.4.6. The capskip package itself declares Node.js 18. I ran 20.11.1 and 24.22.0 with npm 11.19.1.
- A page with a Turnstile widget that you may automate, its URL, and the sitekey from the widget’s data-sitekey attribute.
- An address for CapSkip that your Next.js server can reach: 127.0.0.1 on your own PC, Server mode on a hosted platform.
Everything here ran against two mocks I wrote: one plays the CapSkip in.php and res.php endpoints, the other plays a sign-up page that checks a Turnstile token. The real CapSkip app was sent no task, so no solve time below is a real one, and nothing was deployed to a hosting platform. Turnstile is the example because its call needs only a sitekey and a page URL; any other type the package solves fits the same helper.
Step 1: create the project and keep the secrets server side
Run this in an empty folder in Windows PowerShell. The line that deletes the type field is needed: npm 11.19.1 writes a type of commonjs, and Next.js 16.4.6 then refused to build.
# Windows PowerShell, in an empty folder npm init -y npm pkg delete type npm install next react react-dom capskip server-only npm install -D typescript @types/node @types/react mkdir lib, app\api\turnstile
Create a file named .env.local in that folder. Next.js loads it for next dev and next start. No name starts with NEXT_PUBLIC_, which matters: Next.js replaces a reference to such a variable in browser code with its value at build time. I built with one referenced in a Client Component and its value appeared in a file under .next/static. A prefixed variable that nothing referenced, and one without the prefix, appeared in no file there.
# .env.local CAPSKIP_HOST=127.0.0.1 CAPSKIP_PORT=8080 CAPSKIP_API_KEY=YOUR_API_KEY SOLVE_SECRET=YOUR_LONG_RANDOM_STRING
With API Key Validation off, CapSkip accepts any key value, so the key line only matters once you switch validation on. SOLVE_SECRET is the password for your own route (Step 3). Next.js also needs a root layout:
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}Step 2: one helper that talks to CapSkip
Keep the SDK in one file that only the server can import. Its first line, the server-only import, turns a mistake into a build failure. When a Client Component imported this file, next build stopped with an error saying that server-only cannot be imported from a Client Component module.
// lib/solver.ts
import "server-only";
import { CapSkip } from "capskip";
let client: CapSkip | undefined;
function getClient(): CapSkip {
const host = process.env.CAPSKIP_HOST;
// Without this check the SDK would quietly use 127.0.0.1, which on a
// hosted platform is the platform's own machine.
if (!host) throw new Error("CAPSKIP_HOST is not set");
client ??= new CapSkip({
host,
port: Number(process.env.CAPSKIP_PORT ?? 8080),
apiKey: process.env.CAPSKIP_API_KEY, // only matters with API Key Validation on
});
return client;
}
// timeout is in seconds and covers this one call; see the timing section.
export async function solveTurnstile(sitekey: string, url: string) {
const result = await getClient().turnstile(sitekey, url, { timeout: 40 });
return { token: String(result.code), userAgent: result.userAgent };
}The package ships its own type definitions, so no @types package is needed, and tsc reported no errors for the files in this guide with the strict flag on (TypeScript 7.0.2; the tsconfig.json that Next.js generates leaves strict off). The code field is typed as a string or an object, because some types return an object, so the helper wraps it in String(). The optional userAgent field is, per the package, the User-Agent to use when submitting the token.
Step 3: the Route Handler for your Next.js CAPTCHA solve
The SDK talks to CapSkip through the Node.js http module, so the route must run on the Node.js runtime. The Next.js docs make nodejs the default and mark edge deprecated, and the handler says nodejs anyway. With Cache Components enabled the docs say to remove the runtime export, since Node.js is then the only runtime; I didn’t test that. I switched it to edge to see what happens: the build passed with a deprecation warning, and the first request answered 502 with a message that the Edge runtime does not support the Node.js url module. The SDK wraps the failure in its network exception, so it looks like an unreachable CapSkip.
The route is a public URL that spends your solver, so it solves only the pages in an allow list, for a caller that sends your secret. It refuses when SOLVE_SECRET is unset, because comparing against a header of Bearer undefined would let in anyone who sends that header; that header got a 401 in my run. Object.hasOwn keeps names such as constructor or toString from passing as targets; five such names and a JSON body of null all got a 400.
// app/api/turnstile/route.ts
import { timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";
import { ApiException, NetworkException, TimeoutException } from "capskip";
import { solveTurnstile } from "../../../lib/solver";
export const runtime = "nodejs"; // the SDK uses node:http, so no Edge
export const maxDuration = 60; // seconds; read by the host platform
// Only these pages can be solved, and only for a caller with the secret.
const TARGETS: Record<string, { sitekey: string; url: string }> = {
signup: { sitekey: "YOUR_SITEKEY", url: "https://example.com/signup" },
};
function authorized(header: string | null): boolean {
const secret = process.env.SOLVE_SECRET;
if (!secret || !header) return false;
const given = Buffer.from(header);
const wanted = Buffer.from(`Bearer ${secret}`);
return given.length === wanted.length && timingSafeEqual(given, wanted);
}
export async function POST(request: Request) {
if (!authorized(request.headers.get("authorization"))) {
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
const body = await request.json().catch(() => null);
const name = typeof body?.target === "string" ? body.target : "";
const target = Object.hasOwn(TARGETS, name) ? TARGETS[name] : undefined;
if (!target) return NextResponse.json({ error: "unknown target" }, { status: 400 });
try {
const { token, userAgent } = await solveTurnstile(target.sitekey, target.url);
return NextResponse.json({ token, userAgent });
} catch (err) {
if (err instanceof TimeoutException) {
return NextResponse.json({ error: "solve timed out" }, { status: 504 });
}
if (err instanceof ApiException || err instanceof NetworkException) {
return NextResponse.json({ error: err.message }, { status: 502 });
}
throw err; // a ValidationException is a bug in your code: let it be a 500
}
}An ApiException carries CapSkip’s own answer, such as ERROR_CAPTCHA_UNSOLVABLE, and a new request can help there, as the ERROR_CAPTCHA_UNSOLVABLE guide explains. Before you run it, replace YOUR_SITEKEY and the URL in TARGETS with the sitekey and page of the site you automate, and do the same for PAGE_URL and the sitekey in app/actions.ts further down. Start the dev server in one terminal:
# first terminal, in the project folder npx next dev
Then call the route from a second terminal, with your secret from .env.local:
# second terminal
Invoke-RestMethod -Method Post -Uri http://localhost:3000/api/turnstile `
-Headers @{ Authorization = "Bearer YOUR_LONG_RANDOM_STRING" } `
-ContentType "application/json" -Body '{"target":"signup"}'The reply holds token and userAgent. Put the token in the page’s form field, here cf-turnstile-response, and send that User-Agent with the form. My mock site accepted a token once and answered 403 the second time, which is the mock’s rule, not Cloudflare’s. I ran the flow in next dev and in next build plus next start, on both Node.js versions. The first run also writes a tsconfig.json, and next dev adds an AGENTS.md file; both come from Next.js.
Step 4: or solve and submit in a server action
When the browser never needs the token, solve and submit on the server and send back only the outcome. A server action can do that, and the token stays off the browser. It imports the same helper and adds a Referer, because fetch sends none and some frameworks check it on an HTTPS form submission. It also checks a cookie first, for the reason given after the page file.
// app/actions.ts
"use server";
import { cookies } from "next/headers";
import { solveTurnstile } from "../lib/solver";
const PAGE_URL = "https://example.com/signup";
// Solve and submit in one server-side step, so the token never leaves the server.
export async function signUp(_previous: string, formData: FormData): Promise<string> {
// A server action is a public endpoint: replace this cookie test with
// your own session check.
const secret = process.env.SOLVE_SECRET;
if (!secret || (await cookies()).get("solve-key")?.value !== secret) return "not allowed";
const { token, userAgent } = await solveTurnstile("YOUR_SITEKEY", PAGE_URL);
const reply = await fetch(PAGE_URL, {
method: "POST",
headers: {
Referer: PAGE_URL, // fetch sends no Referer by itself
...(userAgent ? { "User-Agent": userAgent } : {}),
},
body: new URLSearchParams({
email: String(formData.get("email")),
"cf-turnstile-response": token,
}),
});
return `${reply.status} ${(await reply.text()).slice(0, 60)}`;
}A small Client Component runs the action, and the page exports maxDuration for the same reason as the route.
// app/signup-form.tsx
"use client";
import { useActionState } from "react";
import { signUp } from "./actions";
export default function SignupForm() {
const [result, action, pending] = useActionState(signUp, "");
return (
<form action={action}>
<input name="email" defaultValue="[email protected]" />
<button disabled={pending}>{pending ? "Solving..." : "Sign up"}</button>
<p id="result">{result}</p>
</form>
);
}// app/page.tsx
import SignupForm from "./signup-form";
export const maxDuration = 60; // meant for the form's server action; unchecked on hosts
export default function Home() {
return <SignupForm />;
}A server action is a public POST endpoint. Anyone who can load this page can trigger it. Put the page behind your own sign-in, or check a session or secret at the top of signUp(), as the cookie test does. To try it, add a cookie named solve-key holding your secret in the browser’s developer tools. Without a check, a script that replayed the page’s hidden form fields with no credentials got the success text and started a task on the mock.
With the cookie set, a click on the button showed the mock site’s welcome text, and the token never reached the browser. I couldn’t check how a hosting platform applies maxDuration to an action, so test that on yours.
maxDuration against the SDK timeout
The Next.js route segment docs give maxDuration a default that is set by the deployment platform, and self-hosting does not enforce it: with maxDuration at 2 and a mock that needed 5 seconds, next start answered 200 after 7.8 seconds (Node.js 24.22.0). The limit that cuts a solve off is your host’s. The Vercel duration docs list, with Fluid compute on, a default of 300 seconds on every plan and a maximum of 300 on Hobby and 800 on Pro and Enterprise, and say a longer run is terminated. Export a value you chose and check your platform’s numbers; the 30 minute extended maximum it lists as a beta is not covered here.
The SDK polls on a schedule: against the mock it asked for the result at about 0, 0.25, 0.77, 1.78, 3.8, 7.8 and 12.8 seconds, then every 5 seconds. It checks its deadline only when the next poll is due. With a mock that never answered, timeout 5 ended after 7.80 seconds, timeout 10 after 12.83, and the route’s timeout 40 after 42.88 seconds, when the handler returned its 504 (Node.js 24.22.0 and 20.11.1 agreed within 0.1 second). So a call can overrun its timeout by up to 5 seconds. Keep timeout at least 10 seconds under maxDuration, as 40 is under 60 here.
The package’s type comments say Turnstile waits 300 seconds, but in the 1.7.0 source turnstile() passes no timeout, and a call without the option ended at 122.98 seconds, so the 120 second default applied. Pass your own value and the disagreement stops mattering.
A client that gives up doesn’t stop the task. The SDK can’t cancel a call: when my client dropped the request after 1 second, the handler kept polling until its last poll at 37.9 seconds. So keep the timeout short.
Hosted platforms: reach CapSkip with Server mode
On a hosted platform, 127.0.0.1 is the function’s own machine, not your PC. I pointed the handler at a port where nothing listened and got a 502 in 0.06 seconds with the message connect ECONNREFUSED 127.0.0.1 and the port. A deployed function should show the same message for CapSkip on your PC; I deployed nothing to check.
The fix is Server mode: in the connection settings, CapSkip can also accept connections from other devices on your network, or from the internet on a VPS. It needs CapSkip to run as administrator, and the guide says a static public IP gives the most stable remote access. Then set CAPSKIP_HOST in your host’s environment variables to that address and CAPSKIP_PORT to the port. The settings are in the connection settings of the setup guide. Against a mock that listened on all addresses, the handler reached it by my PC’s network address. That checks these settings, not the real Server mode.
CapSkip opens its port to every address when Server mode starts, so to keep it to the machines you expect, add a Windows Firewall block rule for the others. A hosted platform’s egress addresses usually can’t be listed, so the realistic protection there is API Key Validation, where only requests carrying one of your keys are processed, plus a short timeout. The SDK builds a plain http address, so the key travels unencrypted. If your platform offers fixed egress addresses (I didn’t check any), allow only those and keep the block rule for everything else. With validation on and no matching key, my route returned 502.
Common errors
| What you see | Cause | Fix |
|---|---|---|
| Build stops: module format CommonJs does not match | npm init wrote a type of commonjs | Run the npm pkg delete type line from Step 1 |
| Build stops: server-only cannot be imported from a Client Component | A file with use client imports the helper | Call the route or a server action from the client instead |
| 401 unauthorized | Missing or wrong Authorization header, or SOLVE_SECRET unset | Send Bearer and your secret |
| 400 unknown target | The body has no key from the allow list | Send the target name, for example signup |
| 500 and CAPSKIP_HOST is not set in the server log | The variable is empty or unset where the server runs | Set it, then restart or redeploy |
| 502 with ECONNREFUSED | Nothing listens at that host and port, or you are on a hosted platform with 127.0.0.1 | Start CapSkip, or use Server mode |
| 502 saying the Edge runtime does not support a Node.js module | The route runs on the Edge runtime | Export runtime as nodejs |
| 502 with ERROR_KEY_DOES_NOT_EXIST | API Key Validation is on and the key is not in CapSkip’s list | Add the key in CapSkip and set CAPSKIP_API_KEY |
| 502 with ERROR_CAPTCHA_UNSOLVABLE | CapSkip tried and did not pass the challenge | Ask again, see the guide linked in Step 3 |
| 504 solve timed out | No token within the timeout | Check that CapSkip is running, then retry |
| The page refuses a token the second time | A token is single use (a rule of my mock site) | One token per submission |
Every row except ERROR_CAPTCHA_UNSOLVABLE comes from my runs; that one follows the CapSkip docs.
FAQ
Can a Next.js app on Vercel use a CapSkip on my PC?
Yes, through Server mode. CapSkip listens on your network or public IP, the function uses the same HTTP API as locally, and only CAPSKIP_HOST changes. Add a Windows Firewall block rule for machines you don’t expect, and turn on API Key Validation.
Should the route return the token to the browser?
Only if the browser needs it. A server action is safer for the token, which then never reaches the browser, but not for the endpoint: it is public too, so guard it as well. Whichever you choose, every call starts a task on your PC.
Does CapSkip bill per solve when a Next.js route calls it?
No. Wherever the request comes from, the solver is still your own Windows machine, with no per-solve meter on it. Your host may meter the time a function spends waiting for a result.
A Next.js CAPTCHA solve comes down to four settings: the Node.js runtime, a maxDuration above the timeout, secrets without a NEXT_PUBLIC_ name, and a CapSkip address the server can reach. Because the solving happens in a captcha solver on your own PC, a retry costs nothing extra. For other CAPTCHA types see the Node.js CAPTCHA solver page. A host with limits of its own, such as Netlify, is covered in the Netlify Functions guide.
