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.
Installation
Section titled “Installation”npm install @webdecoy/nextjs @webdecoy/nodeMiddleware
Section titled “Middleware”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.
Options
Section titled “Options”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 |
Protecting a Single API Route
Section titled “Protecting a Single API Route”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 });Captcha Handlers
Section titled “Captcha Handlers”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:
import { createCaptchaHandler } from '@webdecoy/nextjs';
export const { GET, POST } = createCaptchaHandler({ secret: process.env.WEBDECOY_CAPTCHA_SECRET!,});Next Steps
Section titled “Next Steps”- Node SDK — the core API, configuration, and detection response
- Browser Client — the widget for the captcha flow