New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

react-spam-shield

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-spam-shield

Free client-side spam protection for React forms

latest
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

React Spam Shield

Free client-side spam protection for React forms with honeypot fields, timing analysis, and behavior tracking. No API keys, no backend required - everything runs in the browser.

Features

  • Zero Configuration: Works out of the box with sensible defaults
  • Privacy First: All processing happens client-side, no data leaves the browser
  • Lightweight: < 10KB minified, zero external dependencies
  • TypeScript: Full TypeScript support with comprehensive type definitions
  • Multiple Detection Methods:
    • Honeypot fields (hidden fields that bots fill)
    • Timing analysis (detects suspiciously fast submissions)
    • Behavior tracking (mouse movements, keyboard interactions)
    • Pattern detection (clipboard events)

Installation

npm install react-spam-shield

Quick Start

import { SpamProtectedForm } from 'react-spam-shield';

function ContactForm() {
  const handleSubmit = (formData, spamScore) => {
    console.log('Spam score:', spamScore);

    // Convert FormData to object
    const data = Object.fromEntries(formData);

    // Send to your backend
    fetch('/api/contact', {
      method: 'POST',
      body: JSON.stringify(data)
    });
  };

  return (
    <SpamProtectedForm
      onSubmit={handleSubmit}
      spamThreshold={0.7}
      onSpamDetected={() => alert('Spam detected!')}
    >
      <input name="name" placeholder="Name" required />
      <input name="email" type="email" placeholder="Email" required />
      <textarea name="message" placeholder="Message" required />
      <button type="submit">Submit</button>
    </SpamProtectedForm>
  );
}

API Reference

SpamProtectedForm

Main component that wraps your form with spam protection.

Props

PropTypeDefaultDescription
childrenReactNodeRequiredForm fields and buttons
onSubmit(data: FormData, spamScore: number) => voidRequiredCalled when form is submitted and passes spam check
spamThresholdnumber0.7Spam score threshold (0-1). Scores above this trigger spam detection
onSpamDetected() => voidundefinedCallback when spam is detected
honeypotFieldNamestring"website"Name of the hidden honeypot field
enableBehaviorTrackingbooleantrueEnable/disable mouse and keyboard tracking
minTimeSecondsnumber2Minimum time before submission is considered valid

Example with All Props

<SpamProtectedForm
  onSubmit={handleSubmit}
  spamThreshold={0.8}
  onSpamDetected={() => console.log('Spam detected!')}
  honeypotFieldName="url"
  enableBehaviorTracking={true}
  minTimeSeconds={3}
>
  {/* Your form fields */}
</SpamProtectedForm>

useSpamDetection Hook

Custom hook for advanced use cases where you need manual control over spam detection.

Return Value

interface SpamDetection {
  calculateSpamScore: () => number;
  setHoneypotFilled: (filled: boolean) => void;
  signals: {
    mouseMovements: number;
    keystrokes: number;
    startTime: number;
    honeypotFilled: boolean;
    clipboardEvents: number;
  };
}

Example

import { useSpamDetection } from 'react-spam-shield';

function CustomForm() {
  const { calculateSpamScore, setHoneypotFilled } = useSpamDetection();

  const handleSubmit = (e) => {
    e.preventDefault();
    const spamScore = calculateSpamScore();

    if (spamScore > 0.7) {
      alert('Spam detected!');
      return;
    }

    // Process form...
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="honeypot"
        style={{ display: 'none' }}
        onChange={(e) => setHoneypotFilled(!!e.target.value)}
      />
      <input name="email" type="email" placeholder="Email" />
      <button type="submit">Submit</button>
    </form>
  );
}

How It Works

Spam Score Calculation

The spam score is calculated based on multiple signals:

Base score = 0

Add to score if:
- Honeypot filled: +0.5
- Submit time < 2 seconds: +0.3
- Mouse movements < 5: +0.2
- Keystrokes < 10: +0.1
- Multiple clipboard pastes (≥2): +0.1

Final score = min(total, 1.0)

Score Interpretation:

  • 0.0-0.3: Very likely human
  • 0.3-0.7: Uncertain
  • 0.7-1.0: Very likely spam

Detection Methods

1. Honeypot Field

A hidden form field that legitimate users won't see or fill, but bots typically auto-fill all fields.

2. Timing Analysis

Tracks time from component mount to form submission. Submissions faster than minTimeSeconds (default 2s) are suspicious.

3. Behavior Tracking

Monitors natural user interactions:

  • Mouse movements
  • Keyboard interactions
  • Clipboard paste events

Real users interact naturally with forms, while bots often submit instantly without interaction.

Advanced Usage

Custom Spam Threshold

Adjust the threshold based on your needs:

// More lenient (fewer false positives)
<SpamProtectedForm spamThreshold={0.8} onSubmit={handleSubmit}>
  {/* ... */}
</SpamProtectedForm>

// More strict (fewer false negatives)
<SpamProtectedForm spamThreshold={0.5} onSubmit={handleSubmit}>
  {/* ... */}
</SpamProtectedForm>

Disable Behavior Tracking

If you have privacy concerns or want to reduce tracking:

<SpamProtectedForm
  enableBehaviorTracking={false}
  onSubmit={handleSubmit}
>
  {/* ... */}
</SpamProtectedForm>

Note: This will only use honeypot and timing analysis for spam detection.

Access Spam Score in Your Backend

const handleSubmit = async (formData, spamScore) => {
  const data = Object.fromEntries(formData);

  // Send spam score to backend for logging/analysis
  await fetch('/api/contact', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      ...data,
      _spamScore: spamScore
    })
  });
};

Browser Support

Works in all modern browsers that support:

  • ES2015
  • React 16.8+ (Hooks)
  • DOM event listeners

Privacy

This package is designed with privacy in mind:

  • All processing happens client-side
  • No data is sent to external servers
  • No tracking cookies or persistent storage
  • Only tracks behavior during the current session

TypeScript

Full TypeScript support included:

import {
  SpamProtectedForm,
  useSpamDetection,
  SpamProtectedFormProps,
  SpamDetection
} from 'react-spam-shield';

Contributing

Found a bug or have a feature request? Please open an issue on GitHub.

License

MIT License - feel free to use in personal and commercial projects.

Changelog

1.0.0

  • Initial release
  • Honeypot field detection
  • Timing analysis
  • Behavior tracking
  • TypeScript support
  • Full documentation

Keywords

react

FAQs

Package last updated on 22 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts