Prog blog
Inventory

How to verify hcaptcha in node.js

How to verify hcaptcha in node.js

If you don't know what hCaptcha is, I suggest you to see hCaptcha website first.

I couldn't find in google information how to verify hcaptcha in node.js, so I'm posting an example of how to do it easily using axios and URLSearchParams.

import axios from 'axios';

export interface HCaptchaSiteVerifyRequest {
  secret: string;
  response: string;
  remoteip?: string;
}

export interface HCaptchaSiteVerifyResponse {
  success: boolean;
  'error-codes'?: string[];
}

const siteVerifyUrl = 'https://hcaptcha.com/siteverify';

export const verifyHCaptcha = async ({
  secret,
  response,
  remoteip,
}: HCaptchaSiteVerifyRequest) => {
  const params: Record<string, string> = remoteip
    ? {
        secret,
        response,
        remoteip,
      }
    : { secret, response };
  const data = new URLSearchParams(params);
  const result = await axios.post<HCaptchaSiteVerifyResponse>(
    siteVerifyUrl,
    data
  );
  return result.data;
};