A React hook that makes it easy to use the Cap.js proof-of-work abuse prevention library in React projects.
This hook adapts and implements the Cap.js widget and worker code and interfaces to make them easier to use in a React application where more control over the UI and implementation are desired. The adapted code replaces the need for workarounds that reference the global Cap.js instance that the widget creates.
npm i @takeshape/use-capBelow is usage similar to invisible mode.
import { useEffect } from 'react';
import { useCap } from '@takeshape/use-cap';
function MyComponent() {
const { solve, reset, solving, progress, error, token } = useCap({
endpoint: "https://my-cap-server.com/api/",
});
useEffect(() => {
if (!token && !error) {
void solve();
}
}, [solve, token, error]);
return (
<form onSubmit>
<h1>use-cap</h1>
<div>Solving: {solving ? 'true' : 'false'}</div>
<div>Progress: {progress ?? '???'}</div>
<div>Token: {token?.token ?? '???'}</div>
<div>Expires: {token?.expires ?? '???'}</div>
<button type="button" onClick={() => reset()}>
Reset
</button>
</div>
);
}You'll likely need the following statements in your CSP:
script-src ... 'wasm-unsafe-eval';
worker-src ... blob:;
If you're using Vite v3 or above, you'll need to prevent it from optimizing this package. It's already optimized!
optimizeDeps: {
exclude: ['@takeshape/use-cap'],
},
- Run a Cap.js standalone server:
docker run -d \
-p 3000:3000 \
-v cap-data:/usr/src/app/.data \
-e ADMIN_KEY=your_secret_key_must_be_30_chars \
--name cap-standalone \
tiago2/cap:latest-
Go to the Cap dashboard and get your Site Key
-
Create an environment file:
cp .env.example .env-
Set the Cap endpoint in the
.envfile -
Run the development app:
npm run dev