Hello everyone, welcome back to Webzone tech tips, I am Zidane,
Today I will share with you step by step how to create a NextJs project with a simple Captcha verifying, using API with
Build a simple captcha with NextJs - Webzone tech tips
The flow verification of captcha
Invalid captcha like this oneCorrect captcha like this one
Step 1: Set up a Next.js project
Create a new Next.js project
npx create-next-app@latest captcha-demo
Step 2: Go inside captch-demo by
cd captcha-demo
Step 3: Install necessary packages,
following the NextJS framework
Step 4: Create the Captcha API Route
src/app/api/captcha/route.ts
We have two API,
GET: will show the captcha when we access the page
POST: will get submit the captcha and verified the captcha.
import { NextResponse } from 'next/server';
interface CaptchaResponse {
question: string;
answer: number;
}
// Handle GET requests
export async function GET() {
const num1 = Math.floor(Math.random() * 10);
const num2 = Math.floor(Math.random() * 10);
const question = `${num1} + ${num2}`;
const answer = num1 + num2;
return NextResponse.json({ question, answer } as CaptchaResponse);
}
// Handle POST requests
export async function POST(request: Request) {
const { userAnswer, correctAnswer } = await request.json();
const isCorrect = parseInt(userAnswer) === correctAnswer;
return NextResponse.json({ isCorrect });
}
This API route will map with src/app/page.tsx when access on localhost:3000/
source code on src/app/page.tsx
'use client'
import { useEffect, useState } from 'react';
interface CaptchaResponse {
question: string;
answer: number;
}
export default function Home() {
const [question, setQuestion] = useState<string>('');
const [userAnswer, setUserAnswer] = useState<string>('');
const [correctAnswer, setCorrectAnswer] = useState<number | null>(null);
const [message, setMessage] = useState<string>('');
const fetchCaptcha = async () => {
const response = await fetch('/api/captcha');
const data: CaptchaResponse = await response.json();
setQuestion(data.question);
setCorrectAnswer(data.answer);
};
useEffect(() => {
fetchCaptcha();
}, []);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await fetch('/api/captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userAnswer, correctAnswer }),
});
const data = await response.json();
if (data.isCorrect) {
setMessage('CAPTCHA verified successfully!');
} else {
setMessage('Incorrect answer. Please try again.');
fetchCaptcha(); // Fetch a new question
}
setUserAnswer(''); // Clear the input field
};
return (
<div style={{ padding: '20px' }}>
<h1 className="title">Simple CAPTCHA Demo By Zidane - Webzone tech tips </h1>
<form onSubmit={handleSubmit}>
<label >
<span className="custom-label"> {question} </span>
<input
type="text"
className="form-control"
value={userAnswer}
onChange={(e) => setUserAnswer(e.target.value)}
required
/>
</label>
<button className='btn' type="submit">Submit</button>
</form>
{message && <p>{message}</p>}
</div>
);
}
My full source code download here
Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about
Build a simple captcha with NextJs - Webzone tech tips ,
please share them in the comments below. I would love to hear from you and discuss this topic further