next-hcaptcha

library pkg

Getting Started

This package provides a simple and easy-to-use React component for integrating hCaptcha into your Next.js applications.

Installation

Install the package using your preferred package manager:

npm install @hcaptcha/react-hcaptcha
# or
yarn add @hcaptcha/react-hcaptcha
# or
pnpm add @hcaptcha/react-hcaptcha

Basic Usage

Here's a simple example of how to use the hCaptcha component in your React application:

import HCaptcha from '@hcaptcha/react-hcaptcha';

function MyForm() {
  const handleVerify = (token: string) => {
    console.log('Captcha token:', token);
  };

  return (
    <form>
      <input type="email" placeholder="Enter your email" />
      <HCaptcha
        sitekey="your-site-key"
        onVerify={handleVerify}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Configuration

Props

The hCaptcha component accepts the following props:

PropTypeRequiredDescription
sitekeystringYesYour hCaptcha site key
onVerifyfunctionYesCallback function called when captcha is verified
onErrorfunctionNoCallback function called when an error occurs
onExpirefunctionNoCallback function called when captcha expires

Environment Variables

Set up your environment variables in .env.local:

NEXT_PUBLIC_HCAPTCHA_SITE_KEY=your-site-key-here
HCAPTCHA_SECRET_KEY=your-secret-key-here

Server-side Verification

To verify the captcha token on the server side, you can use the following approach:

// pages/api/verify-captcha.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { token } = req.body;

  const response = await fetch('https://hcaptcha.com/siteverify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `secret=${process.env.HCAPTCHA_SECRET_KEY}&response=${token}`,
  });

  const data = await response.json();

  if (data.success) {
    res.status(200).json({ success: true });
  } else {
    res.status(400).json({ success: false, error: 'Captcha verification failed' });
  }
}

Advanced Features

Custom Styling

You can customize the appearance of the hCaptcha widget by passing additional props:

<HCaptcha
  sitekey="your-site-key"
  onVerify={handleVerify}
  theme="dark"
  size="compact"
/>

Error Handling

Implement proper error handling to provide a better user experience:

const [captchaError, setCaptchaError] = useState<string | null>(null);

const handleError = (error: string) => {
  setCaptchaError('Captcha verification failed. Please try again.');
  console.error('hCaptcha error:', error);
};

return (
  <div>
    <HCaptcha
      sitekey="your-site-key"
      onVerify={handleVerify}
      onError={handleError}
    />
    {captchaError && (
      <p className="text-red-500 text-sm mt-2">{captchaError}</p>
    )}
  </div>
);

Troubleshooting

Common Issues

Captcha not loading:

  • Check that your site key is correct
  • Verify that your domain is registered with hCaptcha
  • Ensure you're not blocking hCaptcha scripts in your browser

Verification failing:

  • Make sure your secret key is correct on the server side
  • Check that the token hasn't expired (tokens expire after 2 minutes)
  • Verify your server can make outbound HTTPS requests

Debug Mode

Enable debug mode for development:

<HCaptcha
  sitekey="your-site-key"
  onVerify={handleVerify}
  // Add debug prop for development
  {...(process.env.NODE_ENV === 'development' && { 'data-debug': true })}
/>

Best Practices

  1. Always verify on the server side - Never trust client-side verification alone
  2. Handle errors gracefully - Provide clear feedback to users when captcha fails
  3. Use appropriate size and theme - Match your application's design
  4. Test thoroughly - Test on different devices and browsers
  5. Monitor performance - hCaptcha can add load time to your forms

Support

For issues and questions:

More Projects

Explore other projects that might interest you

View all