Files
cap/docs/guide/index.md
T
2025-01-12 13:48:02 +00:00

2.0 KiB

outline
outline
deep

Geting Started

Cap is a library designed for safeguarding against spam and abuse by utilizing a PoW mechanism using both an open-source client-side widget that you can seamlessly integrate with your website and a server-side verification process which typically involves only a few lines of code.

Adding the Cap widget

Cap is built to be straightforward and requires no API tokens for setup. Start by importing the Cap library:

<script src="https://cdn.jsdelivr.net/npm/capdotjs"></script>

::: details Other CDNs While it is recommended to use JSDelivr, you can also import Cap from other CDNs like unpkg or GitHub.

unpkg
<script src="https://unpkg.com/capdotjs"></script>
jsdelivr + GitHub
<script src="https://cdn.jsdelivr.net/gh/tiagorangel1/cap/lib/cap.min.js"></script>
GitHub
<script src="https://raw.githubusercontent.com/tiagorangel1/cap/master/lib/cap.min.js"></script>

:::

Next, add the <cap-widget> component to your HTML.

<cap-widget id="cap" data-api-endpoint="https://<your website url>/api/"></cap-widget>

Note: You'll need to start a server with the Cap API running at the same URL as specified in the data-api-endpoint attribute.

Then, in your JavaScript, listen for the solve event to capture the token when generated:

const widget = document.querySelector("#cap");

widget.addEventListener("solve", function (e) { 
  const token = e.detail.token;
  
  // Handle the token as needed
});

Alternatively, you can use onsolve="" directly within the widget or wrap the widget in a <form></form> (where Cap will automatically submit the token alongside other form data).

Server-Side Validation

Once you have the token, verify it server-side with a simple POST request:

POST <api-endpoint>/validate
Content-Type: application/json

{
  "token": "xxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

The server response will confirm the validity and immediately invalidate the token:

{
  "success": true
}