Adding hCaptcha to NextJS 14 Project

Jay By Jay ·
Adding hCaptcha to NextJS 14 Project

Are you keeping your public forms open to bots? Here is how you can prevent your sender email domain from going to spam and also have protection against bots. When security is paramount, and one of the critical aspects of securing web applications is to distinguish between genuine users and bots. This is where CAPTCHA systems come into play, and hCaptcha has emerged as a robust solution, offering both security and privacy. Let's delve into integrating hCaptcha with a React-Next.js project, ensuring your applications remain secure and user-friendly.

Acquiring Site Key and Secret

You can get the Site Key on hCaptcha dashboard from here and get the account secret key (which is used on the server to verify the submitted token) from here when you add a new site to hCaptcha.

Setting Up hCaptcha in React Frontend

The first step in integrating hCaptcha is to set it up on the React front end. For this guide, we're using the @hcaptcha/react-hcaptcha package, which simplifies the process.

1. Installing the Package

npm install @hcaptcha/react-hcaptcha

2. Implementing hCaptcha in Your Form

In your form component, import HCaptcha from @hcaptcha/react-hcaptcha. You'll need to manage the captcha token through component state and use a ref for the hCaptcha instance.

import React, { useRef, useState } from 'react'; import HCaptcha from '@hcaptcha/react-hcaptcha'; const MyFormComponent = () => { const ref = useRef<HTMLFormElement>(null); const captchaRef = useRef<HCaptcha | null>(null); const [captchaToken, setCaptchaToken] = useState<string | null>(null); const onCaptchaChange = (token: string) => setCaptchaToken(token); const onCaptchaExpire = () => setCaptchaToken(null); // Form submission logic here... const handleFormSubmit = () => { // You'll use the captcha token in this part }; return ( <form ref={ref} onSubmit={handleFormSubmit}> {/* Your form fields go here */} <HCaptcha sitekey="your-site-key" onVerify={onCaptchaChange} ref={captchaRef} onExpire={onCaptchaExpire} /> <button type="submit">Submit Form</button> </form> ); };

In this setup, onCaptchaChange updates the state with the captcha token whenever the captcha is successfully completed, and onCaptchaExpire clears it if the captcha expires.

3. Passing the Captcha Token on Form Submission

When the form is submitted, add the captcha token to the other form data you're sending to the server.

const handleFormSubmit = (event) => { event.preventDefault(); const formData = new FormData(ref.current); formData.append('captcha', captchaToken); // Proceed to send formData to your backend };

Verifying hCaptcha in Next.js Backend

After receiving the captcha token on the backend, you must verify it using the hCaptcha secret key. Here's how to set it up in your Next.js project.

1. Adding the hCaptcha Dependency

We'll use the hcaptcha npm package on the server side.

npm install hcaptcha

2. Verifying the Token

Create a utility or handler function in your Next.js application that uses the verify method from the hcaptcha package.

import { verify } from 'hcaptcha'; const secretKey = process.env.HCAPTCHA_SECRET; export const onNewsLetterFormSubmit = async (formData) => { try { const token = formData.get('captcha')?.toString() || null; if (!token) { return { message: 'Invalid captcha', success: false }; } const { success } = await verify(secretKey, token); if (!success) { return { message: 'Invalid captcha', success: false }; } // Proceed with your form submission logic... return { message: 'Success', success: true }; } catch (error) { return { message: 'Verification failed', success: false }; } };

Ensure that your HCAPTCHA_SECRET environment variable is correctly set in your Next.js project. This function can be leveraged in your API routes or wherever you're handling form submissions.

Integrating hCaptcha with React and Next.js enhances your web application's security, effectively differentiating between real users and bots. By following the above steps, you can set up hCaptcha on both the frontend and backend of your project, making your forms safer without compromising user experience. As you continue

Remain Ahead of the Curve

Stay upto date with the latest Technologies, Trends, Artificial Intelligence, Productivity Tips and more.

No spam. You can unsubscribe at any time.