Skip to content

Next.js Middleware

@webdecoy/nextjs wraps the Node SDK for Next.js: edge middleware that runs before every matched request, a wrapper for individual API routes, and captcha route handlers.

For package capabilities and positioning, see the Next.js bot detection product page.

Terminal window
npm install @webdecoy/nextjs @webdecoy/node
middleware.ts
import { withWebDecoy } from '@webdecoy/nextjs';
import { NextResponse } from 'next/server';
export default withWebDecoy({
threshold: 70,
onBlocked: (request, detection) => {
return NextResponse.json(
{ error: 'Blocked', threat: detection.threat_level },
{ status: 403 }
);
}
});
export const config = {
matcher: ['/api/:path*', '/checkout/:path*']
};

Scope the middleware with Next’s matcher: protect the routes that matter (APIs, login, checkout) and leave static assets untouched.

Send one request with the reserved test User-Agent to a route your matcher covers. It always fires a detection through the real pipeline, works on next dev before you deploy, and shows up labeled Test in the dashboard (excluded from stats and billing):

Terminal window
curl -A "WebDecoy-Test/1.0" http://localhost:3000/api/hello

Within a few seconds a detection with the Test category chip appears on the Detections page. If nothing appears, check that the path is covered by your matcher and that WEBDECOY_API_KEY is set.

Extends the core ProtectOptions (threshold, skipLocalAnalysis, metadata) with:

Option Default Description
getIP x-forwarded-for / x-real-ip Custom IP extraction
onBlocked 403 JSON response Custom NextResponse for blocked requests
onError Log and allow (fail open) Custom error handler

withBotProtection wraps one handler instead of running as global middleware:

import { withBotProtection } from '@webdecoy/nextjs';
async function handler(req, res) {
res.json({ message: 'Protected content' });
}
export default withBotProtection(handler, { blockThreshold: 70 });

createCaptchaHandler generates the route handlers the Browser Client widget needs for the self-hosted captcha flow. Mount it as a catch-all App Router route:

app/__webdecoy/[...webdecoy]/route.ts
import { createCaptchaHandler } from '@webdecoy/nextjs';
export const { GET, POST } = createCaptchaHandler({
secret: process.env.WEBDECOY_CAPTCHA_SECRET!,
});

  • Node SDK: the core API, configuration, and detection response
  • Browser Client: the widget for the captcha flow