next-hcaptcha
Table of Contents
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:
Prop | Type | Required | Description |
---|---|---|---|
sitekey | string | Yes | Your hCaptcha site key |
onVerify | function | Yes | Callback function called when captcha is verified |
onError | function | No | Callback function called when an error occurs |
onExpire | function | No | Callback 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
- Always verify on the server side - Never trust client-side verification alone
- Handle errors gracefully - Provide clear feedback to users when captcha fails
- Use appropriate size and theme - Match your application's design
- Test thoroughly - Test on different devices and browsers
- Monitor performance - hCaptcha can add load time to your forms
Support
For issues and questions:
- Check the official hCaptcha documentation
- Visit the GitHub repository
- Contact hCaptcha support for service-related issues
More Projects
Explore other projects that might interest you
next-api-compose
Simple, dependency free, error aware and powerful utility to compose chain of multiple middleware into one Next.js API Route.
next-api-og-image
:bowtie: Easy way to generate open-graph images dynamically in HTML or React using Next.js API Routes. Suitable for serverless environment.
obj-serialize
Simple utility for serializing objects. Lightweight alternative to 'superjson'. Super useful in Next.js Pages Router