react-spam-shield
v1.0.0
Published
Free client-side spam protection for React forms
Maintainers
Readme
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-shieldQuick 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
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| children | ReactNode | Required | Form fields and buttons |
| onSubmit | (data: FormData, spamScore: number) => void | Required | Called when form is submitted and passes spam check |
| spamThreshold | number | 0.7 | Spam score threshold (0-1). Scores above this trigger spam detection |
| onSpamDetected | () => void | undefined | Callback when spam is detected |
| honeypotFieldName | string | "website" | Name of the hidden honeypot field |
| enableBehaviorTracking | boolean | true | Enable/disable mouse and keyboard tracking |
| minTimeSeconds | number | 2 | Minimum 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 human0.3-0.7: Uncertain0.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
