A simple captcha generator using canvas in JavaScript
npm install captcha-canvas-jsbash
npm install
`
or
`bash
pnpm add captcha-canvas-js
`
---
๐งฑ Usage Example (Basic)
`ts
import { Captcha, MemoryStore } from "captcha-canvas-js";
const captcha = new Captcha(new MemoryStore());
const { id, imageBase64, text } = await captcha.generate();
console.log("Captcha ID:", id);
console.log("Captcha Text:", text); // You may skip logging this in production
console.log("Image (base64):", imageBase64);
// Later verify:
const isValid = await captcha.verify(id, "user-input");
`
---
๐งฉ API
$3
- store: storage object (e.g., MemoryStore, or your own)
- options: optional customization:
`ts
{
width?: number; // default: 120
height?: number; // default: 40
length?: number; // number of characters (default: 4)
fontSize?: number; // default: 28
charset?: string; // default: A-Z + 2-9 (excluding O, I, 1)
background?: string; // e.g., "#f7f7f7"
noise?: number; // number of random lines (default: 3)
}
`
$3
Returns:
`ts
{
id: string;
text: string;
imageBase64: string; // starts with "data:image/png;base64,..."
}
`
$3
Checks if the user input matches the stored captcha text.
---
๐ Storage
$3
In-memory temporary store (auto-expire in 3 minutes by default).
$3
You can implement your own CaptchaStore (e.g., Redis):
`ts
export interface CaptchaStore {
set(id: string, value: string): Promise;
get(id: string): Promise;
delete(id: string): Promise;
}
`
---
๐ Security Notes
- Avoid exposing text in production
- Always expire stored captchas (e.g., 3โ5 minutes)
- Rate limit captcha generation per IP/user if needed
---
๐งช Development
`bash
build for ESM and CommonJS
npm run build
``