Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

Build a simple captcha with NextJs - Webzone tech tips

Thursday, 14 November 2024
|
Read: Completed in minutes

Build a simple captcha with NextJs - Webzone tech tips

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

Build a simple captcha with NextJs - Webzone tech tips

 Invalid captcha like this one

Build a simple captcha with NextJs - Webzone tech tips

Correct captcha like this one

Build a simple captcha with NextJs - Webzone tech tips



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
✋✋✋✋  Webzone Tech Tips, all things Tech Tips for web development  - I am Zidane, See you next time soon ✋✋✋✋

🙇🏼🙇🏼 We Appreciate Your Comments and Suggestions - Webzone, all things Tech Tips web development
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com