If you signed up before June 3, 2021, see the migration guide to learn about the recent API changes.

Prevent fake accounts

A quick guide for adding bot detection using the Filter API, which is an invisible replacement for a CAPTCHA or rate limits and and can be put both in your application and on the edge.

Client-side integration

This guide shows you how to integrate Castle into a web environment using the browser SDK, Castle.js. There are also guides for integrating Castle with native mobile apps.

Step 1. Include Castle.js

Include Castle.js in the <head> section of each page on your site, not just the signup page.

Replace the sample App ID 114165884929488 with the actual one that you’ll find in the Castle dashboard.

<script src="//"></script>

We also provide an npm package that makes it easier to load and use Castle.js as a module, and it will prevent privacy plugins from blocking it.

Step 2. Create a request token

Whenever the user submits a request to you app, for instance during login or registration, you need to create a request_token and pass it as a parameter in the request to your server.

For standard form posts, intercept the submit event for the form you want to protect

<form onsubmit="_castle('onFormSubmit', event)">
  // ....

or call _castle("createRequestToken") to generate single-use token and pass the token to your server with the form data.

_castle('createRequestToken').then(function(token) {
  var requestToken = token
“Single-use” in this context means that a requestToken can actually be used twice per request: once for a call to the Filter API, and one for the Risk API, should you use call both for the same request.

Server-side integration

Start by installing the server-side SDK for Ruby, Python, PHP, Java, or Node

Step 3. Pass the request token to the Castle API

Provide your API Secret as well as the request token string that was passed in the request in the previous step.

See the list of supported event names, as well as the API definition.

Using Ruby on Rails? Use our Devise plugin to get an out-of-the-box protection from fake accounts!
castle =

  token = request.params['castle_request_token']
  context =

  res = castle.filter(
    event: '$registration',
    request_token: token,
    context: {
      ip: context[:ip],
      headers: context[:headers]

  if res[:risk] > 0.9
    # IMPLEMENT: Deny attempt

rescue Castle::Error => e
  # Handle error
try {
  $token = $_POST['castle_request_token'];

  $res = Castle::filter([
    'event' => '$registration',
    'request_token' => $token,
    'context' => [
      'ip' => Castle_RequestContext::extractIp(),
      'headers' => Castle_RequestContext::extractHeaders()

  if ($res->risk > 0.9) {
    // IMPLEMENT: Deny attempt

} catch (Castle_Error $e) {
  // Handle error
    token = request.form['castle_request_token'] # Using Flask
    context =

    client = Client()

    res = client.filter({
        'event': '$login',
        'request_token': token,
        'context': {
          'ip': context['ip'],
          'headers': context['headers']

    if res['risk'] > 0.9:
        # IMPLEMENT: Deny attempt

except CastleError as e:
     # Handle error
String token = request.getParameter("castle_request_token");

Castle castle = Castle.initialize();
CastleContextBuilder context = castle.contextBuilder().fromHttpServletRequest(request)

try {
  CastleResponse response = castle.client().filter(ImmutableMap.builder()
    .put(Castle.KEY_EVENT, "$login")
    .put(Castle.KEY_CONTEXT, ImmutableMap.builder()
      .put(Castle.KEY_IP, context.getIp())
      .put(Castle.KEY_HEADERS, context.getHeaders())
    .put(Castle.KEY_USER, ImmutableMap.builder()
      .put(Castle.KEY_USER_ID, user.getId())
      .put(Castle.KEY_EMAIL, user.getEmail())
      .put("username", user.getUsername())
    .put(Castle.KEY_REQUEST_TOKEN, token)
} catch (CastleRuntimeException runtimeException) {
  // Handle error

float risk = response.json()

if (risk > 0.9) {
  // IMPLEMENT: Deny attempt
try {
  var token = request.body["castle_request_token"]; // Using Express

  const castle = new Castle({ apiSecret: 'YOUR SECRET HERE' });
  const context =, {}, castle.configuration);

  const res = castle.filter({
    event: '$registration',
    request_token: token,
    user: {
    context: {
      ip: context.ip,
      headers: context.headers

  if (res.risk > 0.9) {
    // IMPLEMENT: Deny attempt
} catch (e) {
As a starting point, it’s recommended that you deny any attempts where the risk score is above 0.9.

The API response can be used to write granular risk logic. Read the complete list of signals and the guide on Policies for more information.

  "risk": 0.95,
  "signals": {
    "bot_behavior": {},
    "proxy_ip": {},
    "disposable_email": {},
    "spoofed_device": {}
  "policy": {
    "action": "deny",
    "name": "Block bots",
    "id": "e14c5a8d-c682-4a22-bbca-04fa6b98ad0c",
    "revision_id": "b5cf794e-88c0-426e-8276-037ba1e7ceca"

🎉 Congratulations! – You have now completed a basic integration of Castle!