Server Integration

Node.js SDK

Server-side integration for your Node.js backend. As of v0.3.0, run a self-hosted captcha and in-process bot detection with no third-party calls for scoring.

Installation
npm install @webdecoy/node

// or
yarn add @webdecoy/node

// or
pnpm add @webdecoy/node

What the SDK Does

The Node.js SDK provides server-side utilities for working with WebDecoy detections.

Verify Detections

Server-side verification of bot scanner results to prevent client-side tampering.

Query Detections

Access your detection history and analytics data through the API.

Webhook Validation

Validate HMAC signatures on incoming webhook payloads.

New in v0.3.0

Self-Hosted Captcha and In-Process Detection

The SDK now scores requests inside your own process. The detection engine and a proof-of-work captcha run on your server with no third-party call for scoring. Only optional IP enrichment uses the WebDecoy API.

In-Process Detection Engine

DetectionEngine scores around 40 signals across vision-AI, headless, automation, behavioral, fingerprint, JA3/JA4, and keystroke-cadence detectors into an allow, challenge, or block verdict. No remote call.

Proof-of-Work Captcha

HMAC-signed SHA-256 challenges with difficulty scaling, replay protection, and the signals bound into the work. Issues single-use, IP-bound session tokens. A self-hosted alternative to reCAPTCHA, hCaptcha, and Turnstile.

Browser Widget

The new @webdecoy/client package collects the signals, solves the proof-of-work, and submits to your server. Checkbox, invisible, and on-demand modes.

Browser (@webdecoy/client)
import { WebDecoyCaptcha } from '@webdecoy/client';

WebDecoyCaptcha.configure({
  serverUrl: 'https://your-server.com'
});

// Checkbox widget
WebDecoyCaptcha.render('captcha-box', {
  siteKey: 'pk_live_...',
  callback: (token) => submit(token)
});

// Or protect a form invisibly
WebDecoyCaptcha.invisible({ siteKey: 'pk_live_...' });
Server (@webdecoy/express)
import express from 'express';
import { webdecoyCaptcha } from '@webdecoy/express';
import { Captcha } from '@webdecoy/node';

const app = express();
app.use(express.json());

// Serves /__webdecoy/challenge, /verify,
// /score, and /token/verify
app.use(webdecoyCaptcha({
  secret: process.env.WEBDECOY_SECRET
}));

// Verify the token on a protected route
const captcha = new Captcha({
  secret: process.env.WEBDECOY_SECRET
});

app.post('/login', (req, res) => {
  const { valid } = captcha.verifyToken(
    req.body.webdecoy_token,
    req.ip
  );
  if (!valid) {
    return res.status(403).json({ error: 'captcha failed' });
  }
  // proceed with login
});

Read the deep dive: Self-Hosted Captcha for Node.js (SDK v0.3.0)

Basic Usage

Quick Start

Initialize the SDK with your API key and start verifying bot scanner results from your backend.

API Key Authentication

Use your API key from the WebDecoy dashboard

Async/Await Support

Modern Promise-based API

TypeScript Types

Full type definitions included

Example Usage
import { WebDecoy } from '@webdecoy/node';

const webdecoy = new WebDecoy({
  apiKey: process.env.WEBDECOY_API_KEY
});

// Verify a bot scanner token
app.post('/api/submit', async (req, res) => {
  const token = req.headers['x-webdecoy-token'];

  const result = await webdecoy.verify(token);

  if (result.isBot && result.score > 70) {
    return res.status(403).json({
      error: 'Bot detected'
    });
  }

  // Process legitimate request
});
Webhook Validation
import { validateWebhook } from '@webdecoy/node';

app.post('/webhooks/webdecoy', (req, res) => {
  const signature = req.headers['x-webdecoy-signature'];
  const payload = req.body;

  const isValid = validateWebhook(
    payload,
    signature,
    process.env.WEBHOOK_SECRET
  );

  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }

  // Process the detection event
  const { detection_type, threat_score, ip } = payload;

  console.log(`Detection: ${detection_type}, Score: ${threat_score}`);

  res.status(200).send('OK');
});
Security

Webhook Validation

All webhooks from WebDecoy are signed with HMAC-SHA256. The SDK provides utilities to validate these signatures.

HMAC-SHA256 signature verification
Timestamp validation to prevent replay attacks
Constant-time comparison

Framework-Specific Packages

Install the core SDK or use our framework-specific packages with built-in middleware.

Core SDK

npm install @webdecoy/node

Works with any framework

Browser Client

npm install @webdecoy/client

Captcha widget

Express

npm install @webdecoy/express

Middleware included

Fastify

npm install @webdecoy/fastify

Plugin included

Next.js

npm install @webdecoy/nextjs

Middleware wrapper

Express.js

Express Middleware

The Express package provides middleware that automatically analyzes every request and attaches detection results.

Global or per-route middleware
Configurable block threshold
Path exclusions for static assets
Detection results on req.webdecoy
Express Middleware
import express from 'express';
import { webdecoyMiddleware } from '@webdecoy/express';

const app = express();

// Apply globally
app.use(webdecoyMiddleware({
  apiKey: process.env.WEBDECOY_API_KEY,
  sensitivity: 'medium',
  blockThreshold: 70,
  exclude: ['/health', '/static/*']
}));

// Or per-route
app.post('/api/login',
  webdecoyMiddleware({ blockThreshold: 50 }),
  (req, res) => {
    // Access detection results
    const { score, threatLevel } = req.webdecoy;

    if (req.webdecoy.shouldChallenge()) {
      return res.status(429).json({
        error: 'Please complete verification'
      });
    }

    // Process login...
  }
);
Fastify Plugin
import Fastify from 'fastify';
import webdecoyPlugin from '@webdecoy/fastify';

const fastify = Fastify();

// Register the plugin
await fastify.register(webdecoyPlugin, {
  apiKey: process.env.WEBDECOY_API_KEY,
  sensitivity: 'medium'
});

fastify.post('/api/checkout', async (req, reply) => {
  // Detection attached to request
  const detection = req.webdecoy;

  if (detection.score > 80) {
    return reply.code(403).send({
      error: 'Request blocked'
    });
  }

  if (detection.shouldChallenge()) {
    return reply.code(429).send({
      error: 'Verification required',
      challengeUrl: '/verify'
    });
  }

  // Process checkout...
});
Fastify

Fastify Plugin

Register WebDecoy as a Fastify plugin. Detection data is automatically attached to every request object.

Native Fastify plugin architecture
Async/await throughout
High-performance request handling
Full TypeScript support
Next.js

Next.js Middleware

Protect your Next.js app at the edge with middleware that runs before every request.

Edge Runtime compatible
App Router and Pages Router support
Route-level protection decorators
Server Actions protection
middleware.ts
import { withWebDecoy } from '@webdecoy/nextjs';
import { NextResponse } from 'next/server';

export default withWebDecoy({
  apiKey: process.env.WEBDECOY_API_KEY,

  // Handle detection results
  onDetection: async (detection, request) => {
    if (detection.score > 80) {
      return NextResponse.json(
        { error: 'Blocked' },
        { status: 403 }
      );
    }

    if (detection.shouldChallenge()) {
      return NextResponse.redirect(
        new URL('/verify', request.url)
      );
    }

    return NextResponse.next();
  }
});

export const config = {
  matcher: ['/api/:path*', '/checkout/:path*']
};

Detection Response

Every detection returns a comprehensive analysis with actionable methods.

Detection Object
{
  "score": 78,
  "threatLevel": "HIGH",
  "flags": [
    "headless_browser",
    "webdriver_detected",
    "canvas_anomaly"
  ],
  "signals": {
    "webdriver": true,
    "headless": true,
    "canvasAnomaly": true,
    "mouseEntropy": 0.12
  },
  "ip": "203.0.113.42",
  "userAgent": "Mozilla/5.0...",
  "timestamp": "2025-12-13T22:30:00Z"
}

Threat Levels

MINIMAL (0-29): Likely human
LOW (30-49): Some signals
MEDIUM (50-69): Suspicious
HIGH (70-89): Likely bot
CRITICAL (90-100): Confirmed bot

Helper Methods

shouldBlock() Score ≥ block threshold
shouldChallenge() Score in challenge range
isLegitimate() Score below thresholds

Why Use Server-Side Bot Detection

Client-side detection is powerful, but server-side verification makes it tamper-proof.

Tamper-Proof Verification

Attackers cannot modify bot scores or bypass detection by manipulating client-side JavaScript. Server verification is the final authority.

TLS Fingerprinting

The SDK adds JA3/JA4 TLS fingerprint analysis that can only be done server-side, catching bots that spoof browser user agents.

Real-Time Webhooks

Receive instant notifications when bots are detected. Trigger automated responses in your backend without polling.

Available SDKs

WebDecoy provides official SDKs for multiple languages and platforms.

Node.js

Express, Next.js, NestJS, Fastify. Full TypeScript support.

npm install @webdecoy/node

Go

High-performance Go SDK for net/http handlers.

View Go documentation

PHP / WordPress

WordPress plugin and PHP SDK for custom integrations.

View PHP documentation

Frequently Asked Questions

Common questions about the WebDecoy Node.js SDK.

Why do I need server-side verification with the SDK?

Client-side bot detection can be tampered with by sophisticated attackers. The SDK allows you to verify detection tokens server-side, ensuring that bot scores have not been modified. This two-layer approach combines client-side signals with tamper-proof server verification.

Which Node.js frameworks are supported?

The SDK works with any Node.js framework including Express, Fastify, Next.js, NestJS, Koa, and Hapi. It provides simple middleware integration patterns and works with both JavaScript and TypeScript projects with full type definitions included.

How do I validate incoming webhooks from WebDecoy?

The SDK includes a validateWebhook function that verifies HMAC-SHA256 signatures on incoming webhook payloads. This ensures webhooks are genuinely from WebDecoy and have not been tampered with. The function also validates timestamps to prevent replay attacks.

What data does the verification response include?

Verification responses include the bot score (0-100), detection signals (webdriver, headless, canvas anomaly, etc.), a human/bot verdict, the visitor ID, and the timestamp. You can use this data to make access control decisions in your application.

Are there SDKs for other languages besides Node.js?

Yes. WebDecoy also provides SDKs for Go and PHP (with WordPress integration). All SDKs support the same core functionality: token verification, webhook validation, and API access. See our documentation for Go and PHP integration guides.

Does the SDK send my traffic to a third party for scoring?

Not in v0.3.0. The detection engine and proof-of-work captcha run in your own process, so the allow, challenge, or block decision is made locally with no remote call. The only optional outbound request is IP enrichment (VPN, proxy, Tor, abuse score, geo) against the WebDecoy API, which you can disable.

Can WebDecoy replace reCAPTCHA, hCaptcha, or Turnstile?

Yes. v0.3.0 ships a self-hosted captcha: an HMAC-signed proof-of-work challenge plus the @webdecoy/client browser widget. You hold the signing secret and the widget posts to your own domain, so there is no third-party captcha script watching your visitors. It runs as a checkbox, invisibly, or on demand.

Ready to integrate server-side bot detection?

Install the Node.js SDK and start verifying bot scanner results in minutes.

View npm Package