Build efficient contact forms with Next.js and Netlify and integrate powerful spam detection! This article will guide you to create a contact form with a confirmation page and use Netlify's built-in capabilities to improve anti-spam capabilities.
Next.js is a powerful React framework that can build high-performance, scalable React applications. Combined with Netlify, you can quickly build a contact form without writing server-side code.
Netlify forms are convenient to set up and the free version is available (each Netlify site can submit a form up to 100 free times). Submitted forms are automatically passed through Netlify's built-in spam filter (using Akismet) and offer a variety of configuration options to enhance spam detection.
Create a contact form
In the Next.js application, create a ContactForm
component to render forms on the contact page. If you want the form to render under the /contact
path, you should use the following ContactForm
component in pages/contact.js
file, including the tags and input fields:
const ContactForm = (/* code see */ below);
The following code snippet creates a form with name, company, email and message fields, and a submit button. After submitting the form, it will be redirected to /contact/?success=true
according to the form's action
attribute value. Currently, there is no difference in how the page looks when it comes with and without success
query parameters, and we will update it later.
The current Contact.js
file is as follows:
import React from "react"; const ContactPage = () => { const ContactForm = (/* code in the above code snippet*/) Return ( <div> <h1 id="Contact-Us">Contact Us</h1> {ContactForm} </div> ); }; export default ContactPage;
Once we have finished setting up the basic form, we need to add some information so that Netlify automatically recognizes the form in future site deployments. To do this, you need to update the form, add data-netlify="true"
property and a hidden input field containing the form name. In the Netlify dashboard, navigate to your site and click the Forms tab to view the form response based on the name set in the hidden field. Importantly, if there are multiple forms in the site, you should set a unique name for each form so that Netlify records correctly.
{/* See below for code*/}
After successfully deploying the site to Netlify and adding the data-netlify
attribute and form-name
field, you can access the deployed site and fill in the form. After submitting the form, navigate to https://app.netlify.com/sites/site-name/forms
(where site-name
is your site name), and if the form is set successfully, the latest form submission history should be displayed.
Redirect to the confirmation page
To improve the user experience, we should add some logic to redirect to the confirmation page after the form is submitted when the URL changes to /contact/?success=true
. You can also choose to redirect to a completely different page when the form is submitted, but using query parameters can use Next Router to achieve a similar effect. We can create a new variable to determine the visibility of the confirmation page or form based on the query parameters. You can use the next/router
import { useRouter } from "next/router";
to retrieve the current query parameters.
const router = useRouter(); const confirmationScreenVisible = router.query?.success && router.query.success === "true";
In this example, it is not possible to be visible on the page and form at the same time; therefore, you can use the following statement to determine whether the form is visible:
const formVisible = !confirmationScreenVisible;
To give users the option to resubmit the form, you can add a button to the confirmation page to reset the form by clearing the query parameters. Using router.replace
(rather than router.push
) not only updates the page, but also replaces the current page with a version that does not contain query parameters.
router.replace("/contact", undefined, { shallow: true })
We can then render the form conditionally based on whether it is visible or not:
{formVisible? ContactForm: ConfirmationMessage}
Based on the above, we can use the following code to render the form conditionally based on query parameters (updated when form is submitted):
import React, { useState } from "react"; import { useRouter } from "next/router"; const ContactPage = () => { const [submitterName, setSubmitterName] = useState(""); const router = useRouter(); const confirmationScreenVisible = router.query?.success && router.query.success === "true"; const formVisible = !confirmationScreenVisible; const ConfirmationMessage = (); const ContactForm = (/* code in the first code example*/); Return ( Thank you for submitting the form. We will contact you within 24-48 hours.
); }; export default ContactPage;Contact Us
{formVisible? ContactForm: ConfirmationMessage}
Add hidden robot fields
Now that the core functionality of the form is complete, we can add additional spam detection to the form in addition to the Akismet included by default. This feature can be enabled by adding data-netlify-honeypot="bot-field"
property to the form.
{/* See below for code*/}
We also need to create a new hidden paragraph with a tag called bot-field
that contains the input. This field is "visible" to the robot, but not to humans. When this hidden field is filled in, Netlify detects the bot and marks the submission as spam.
<p hidden> <label>Please do not fill in this item:</label> <input type="text" name="bot-field"> </p>
Further customization
- We can explore another spam protection option supported by Netlify, which is to add reCAPTCHA 2 to Netlify forms.
- We can update the form and allow uploading of files.
- We can set notifications for form submissions. This can be set in
https://app.netlify.com/sites/[your-site-name]/settings/forms
where we can include a custom topic field (can be hidden) for email notifications.
Complete code
The complete site code is available on GitHub. (Please provide a GitHub link if there is one in the article)
Extra content
The following code contains everything we discussed, as well as the logic to set up custom subject lines using what is submitted in the Name field. (Please provide the code)
Please note that the above code snippet needs to be supplemented with the complete code according to the original document. I tried my best to rewrite and polish based on the original document, striving to make pseudo-original creation without changing the original meaning.
The above is the detailed content of How to Create a Contact Form With Next.js and Netlify. For more information, please follow other related articles on the PHP Chinese website!

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

Deploying like an idiot comes down to a mismatch between the tools you use to deploy and the reward in complexity reduced versus complexity added.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),