[email protected] #168457
              
  
  Closed
              
          
                  
                    
                      01767051159
                    
                  
                
                  started this conversation in
                Universe
              
            
            
              [email protected]
            
            #168457
          
          
        Replies: 0 comments
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Uh oh!
There was an error while loading. Please reload this page.
-
title: Developer Guide
slug: /
hCaptcha can help protect your applications from bots, spam, and other forms of automated abuse.
Installing the SDK is fast and easy: either add a few lines of HTML and server side code, or use one of the many tools that natively support hCaptcha.
To make integration quick, plugins and code examples are available for many frameworks: Angular, Node, Express, ReactJS, VueJS, WordPress and many more. Mobile App SDKs are also available.
A complete list of known hCaptcha integrations is also available if you'd like to submit a new one.
Switching from reCAPTCHA
If you're already using Google's reCAPTCHA, you can use your existing code with only a few changes. hCaptcha methods are API-compatible with reCAPTCHA methods, for example
render()andonload(). Custom data attributes liketheme,size, andtab-indexare also supported in the same way by hCaptcha.Quick Start
Frontend code example (simple)
Frontend code example (programmatic JS)
api.hcaptcha.com/siteverify). hCaptcha says it is valid. Your server now knows the user is not a bot and lets them log in. Pretty simple!Backend code example
Request Flow
sequenceDiagram participant User participant Your Website or App participant hCaptcha Client API participant Your Server participant hCaptcha Siteverify User->>Your Website or App: Load Website or App Your Website or App->>User: Load hCaptcha JS or SDK User->>hCaptcha Client API: Please issue passcode hCaptcha Client API->>User: Returns challenge or passcode hCaptcha Client API->>Your Website or App: Passcode embedded in form or returned via JS/callback Your Website or App->>Your Server: Form or XHR with hCaptcha passcode Your Server->>hCaptcha Siteverify: Is this passcode valid? hCaptcha Siteverify->>Your Server: Passcode is valid (success is true) Your Server->>User: Session authorized, proceedContent-Security-Policy Settings
Content Security Policy (CSP) headers are an added layer of security that help to mitigate certain types of attacks, including Cross Site Scripting (XSS), clickjacking, and data injection attacks.
If you use CSP headers, please add the following to your configuration:
script-srcshould includehttps://hcaptcha.com, https://*.hcaptcha.comframe-srcshould includehttps://hcaptcha.com, https://*.hcaptcha.comstyle-srcshould includehttps://hcaptcha.com, https://*.hcaptcha.comconnect-srcshould includehttps://hcaptcha.com, https://*.hcaptcha.comPlease do not hard-code specific subdomains, like
newassets.hcaptcha.com, into your CSP: asset subdomains used may vary over time or by region.If you are an enterprise customer and would like to enable additional verification to be performed, you can optionally choose the following CSP strategy:
unsafe-evalandunsafe-inlineshould includehttps://hcaptcha.com, https://*.hcaptcha.comAdd the hCaptcha Widget to your Webpage
hCaptcha requires two small pieces of client side code to render a widget on an HTML page. First, you must include the hCaptcha javascript resource somewhere in your HTML page. The
<script>must be loaded via HTTPS and can be placed anywhere on the page. Inside the<head>tag or immediately after the.h-captchacontainer are both fine.Second, you must add an empty DOM container where the hCaptcha widget will be inserted automatically. The container is typically a
<div>(but can be any element) and must have classh-captchaand adata-sitekeyattribute set to your public sitekey.:::info
The sitekey is our unique identifier for your site, app, or flow.
You can set behavior and track statistics per-sitekey. This lets you choose the granularity you need, whether that is a single sitekey used across many sites or one sitekey per flow, e.g. one for signup and one for login.
You were automatically assigned a sitekey when you created an account. We've
included your actual sitekey in all the examples here. It is{' '}
{user.sitekey}and can be found on your{' '}profile page for
future reference.
:::
Typically, you'll want to include the empty
.h-captchacontainer inside an HTML form. When a challenge is successfully passed, a hidden token will automatically be added to your form that you can then POST to your server for verification. You can retrieve it server side with POST parameterh-captcha-response.Here's a full example where hCaptcha is being used to protect a signup form from automated abuse. When the form is submitted, the
h-captcha-responsetoken will be included with the email and password POST data after the challenge is passed.Verify the User Response Server Side
By adding the client side code, you were able to render an hCaptcha widget that identified if users were real people or automated bots. When the challenge succeeded, the hCaptcha script inserted a unique token into your form data.
To verify that the token is indeed real and valid, you must now verify it at the API endpoint:
The endpoint expects a POST request with two parameters: your account secret and the
h-captcha-responsetoken sent from your frontend HTML to your backend for verification. Do not send JSON data: the endpoint expects a standard URL-encoded form POST.Additionally, you should include the user's IP address for enhanced security. While not strictly required, providing the IP address helps improve verification accuracy. For Enterprise customers, this also enables risk scores.
A simple test will look like this:
curl https://api.hcaptcha.com/siteverify \ -X POST \ -d "secret=YOUR-SECRET&remoteip=CLIENT-IP&response=CLIENT-RESPONSE"CLIENT-RESPONSEis the token returned by the hCaptcha SDK to the client.YOUR-SECRETis your sitekey secret ("ES_...") that you generated in the dashboard.CLIENT-IPis the client's IP address. Whileremoteipis not strictly required, providing it helps improve verification accuracy.The endpoint expects the
application/x-www-form-urlencodedContent-Type. You can see exactly what is sent usingin the example above.
Do not use a GET request to call /siteverify. Use a POST request, and pass the parameters in the form body, not the URL.
While the endpoint may respond correctly to a GET request or to a POST request that uses URL parameters, this is not guaranteed. If the parameters you send to GET are too long, the request will fail and you will be unable to validate passcodes. Using a POST request ensures you will not have this problem.
Please note that you must call
/siteverifywith your account secret in order to validate passcodes users send you are real and unexpired. You will also be unable to validate passcodes from a sitekey in one account if using a different account's secret.:::info
Since you are logged in, we have included your actual secret key in the
examples here. You can also find it on your{' '}
profile page for
future reference.
:::
Tokens can only be used once and must be verified within a short period of time after being issued. To retrieve the token on your server, use the
h-captcha-responsePOST parameter submitted by your form.We recommend passing the sitekey parameter, as it will prevent tokens issued on one sitekey from being redeemed elsewhere. Depending on your difficulty settings this might have no security impact, but if you set a higher difficulty level and do not enforce sitekey matches an adversary could potentially solve an easier challenge on another sitekey, then redeem it on a harder one.
Your POST request will receive a JSON response. You should check the
successfield and only execute your normal business logic ifsuccessistrue. Otherwise, check theerror-codesfield for a human-readable error code and return an appropriate error message to the end user, or a generic error message if no details are specified inerror-codes.Here's what a JSON response from hCaptcha looks like:
{ "success": true|false, // is the passcode valid, and does it meet security criteria you specified, e.g. sitekey? "challenge_ts": timestamp, // timestamp of the challenge (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) "hostname": string, // the hostname of the site where the challenge was passed "credit": true|false, // optional: deprecated field "error-codes": [...] // optional: any error codes "score": float, // ENTERPRISE feature: a score denoting malicious activity. "score_reason": [...] // ENTERPRISE feature: reason(s) for score. }(See hCaptcha.com/enterprise for details on hCaptcha Enterprise features like bot scores, passive and nearly passive "No-CAPTCHA" modes, and more.)
Please note that the credit field is not always included, and is scheduled for deprecation in Q3 2023.
Please also note that the hostname field is derived from the user's browser, and should not be used for authentication of any kind; it is primarily useful as a statistical metric. Additionally, in the event that your site experiences unusually high challenge traffic, the hostname field may be returned as "not-provided" rather than the usual value; all other fields will return their normal values.
Siteverify Error Codes Table
These are the error codes that can be returned by the hCaptcha API:
Rotating Your Siteverify Secret
Your siteverify secret is solely for secure machine-to-machine authentication; it should never be exposed publicly.
If your siteverify secret has been unintentionally exposed, you may receive an email warning from us.
You can also rotate it yourself at any time by visiting the Dashboard, choosing your profile icon and Settings menu option, and then clicking
Generate New Secret. Make sure to copy that value! We don't retain it, so you won't be able to see it again.You will receive an email confirmation within a few seconds of rotation.
Note: Free users may rotate the secret once per day. Pro users may rotate secrets up to 3 times per day. Enterprise users have additional options to manage secrets.
For example, Enterprise accounts can create multiple Sitekey Secrets with an optional expiry and assign secrets to one or many sitekeys to enable segmentation of secrets by environment, unique keys per team, and more. Please see the Enterprise docs for more details.
Local Development
If you are developing on your local machine there are a few things to keep in mind.
Modern browsers have strict CORS and CORB rules, so opening a
[REDACTED] that loads hCaptcha will not work. Loading hCaptcha fromhttp://localhost/` will encounter the same issue on some browsers. The hCaptcha API also prohibitslocalhostand127.0.0.1as supplied hostnames.The simplest way to circumvent these issues is to add a hosts entry. For example:
Place this in
/etc/hostson Linux,[REDACTED] on Mac OS X, orC:\Windows\System32\Drivers\etc\hosts` on Windows.You can then access your local server via http://test.mydomain.com, and everything will work as expected.
TypeScript Types
How to install
You can install our typescript types @hcaptcha/types for the
hcaptchaglobal variable using your preferred package manager:or
How to use
Locally
or
Globally
Add import or reference to your
.d.ts:Or add
"node_modules/@hcaptcha"to thetypeRootsintsconfig.json{ "compilerOptions": { // ... "typeRoots": [ "node_modules/@hcaptcha" ] // ... }, // ... }Integration Testing: Test Keys
If you intend to run automated integration tests that access a live server, the simplest approach is to use the following test hCaptcha sitekeys that always generate a passcode without asking a question. Those passcodes can only be verified using the test secret.
:::caution
The test keys provide no anti-bot protection, so please double-check that you use them only in your test environment!
:::
Test Key Set: Publisher or Pro Account
10000000-ffff-ffff-ffff-0000000000010x000000000000000000000000000000000000000010000000-aaaa-bbbb-cccc-000000000001This keypair will never challenge and always produce the same response token, which will return
success: truewhen passed to the endpoint with this secret. Thesiteverifyresponse will have the fields found in Publisher and Pro accounts.If you are an Enterprise customer, please instead use the test keypairs below to ensure you are consuming
scoreand other Enterprisesiteverifyfields.Test Key Set: Enterprise Account (Safe End User)
20000000-ffff-ffff-ffff-0000000000020x000000000000000000000000000000000000000020000000-aaaa-bbbb-cccc-000000000002Test Key Set: Enterprise Account (Bot Detected)
30000000-ffff-ffff-ffff-0000000000030x000000000000000000000000000000000000000030000000-aaaa-bbbb-cccc-000000000003For hCaptcha Enterprise users, the two keypairs above will allow you to verify your application behavior in the most common score scenarios. Please contact your integration support engineers for guidance if you have additional questions.
Frontend Testing: Force a Visual Challenge
Sometimes you want to force a visual challenge to make sure everything looks they way you expect when a challenge modal is triggered.
If you are an Enterprise customer, just add a "Challenge" rule targeting your IP or user agent.
If you are using the Pro or free service, one option is to add a second sitekey set to "Always Challenge" mode. Note that "challenge" does not automatically mean "visual challenge" in our system, but if you rapidly reload several times you are likely to start seeing visual challenges.
Backend Testing: Ensure Correct Handling of Rejected Tokens
If the token the user sends to you is invalid or expired, the
siteverifyresponse will containsuccess: false. This means you can safely block the request.To test this, simply use a nonsense string like "FAKE-TOKEN" in your backend integration tests when you want to validate end-to-end failure behavior.
What's next?
Congrats! By following this guide, you now have a complete and working implementation of hCaptcha. By default, hCaptcha supports multiple widgets per page and automatic localization.
If you're interested in a more advanced implementation that involves JavaScript callbacks, explicit rendering, alternative themes, or explicit localization, check out the next section on configuration.
And if you have any issues getting hCaptcha to work on your site, or you'd like to start a pilot of our enterprise service to try out bot scores, No-CAPTCHA modes, and more, get in touch and we'll be happy to help.
Beta Was this translation helpful? Give feedback.
All reactions