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.

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.

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

OptionDefaultDescription
getIPx-forwarded-for / x-real-ipCustom IP extraction
onBlocked403 JSON responseCustom NextResponse for blocked requests
onErrorLog 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