Developing Secure Contact Forms in Next.js with Modern Practices
Contact forms are critical for web applications, serving as a primary channel for communication between users and site administrators. With the rise of sophisticated cyber threats, ensuring form security is paramount. In this article, we’ll explore developing secure contact forms in Next.js using modern practices. We’ll incorporate TypeScript to enhance code quality and maintainability.
Why Security Matters
Before we dive into the technical implementation, let’s briefly discuss the significance of form security:
- Data Privacy: Users trust websites to handle their data responsibly. Protecting this information is crucial for maintaining user trust.
- Preventing Spam: Contact forms are often targeted by bots that flood email inboxes with junk submissions.
- Compliance: Regulations like GDPR make data protection not just a priority but a legal requirement.
Setting Up a Next.js Project
To begin, let’s set up a basic Next.js project and integrate TypeScript.
npx create-next-app@latest my-secure-form --typescript
cd my-secure-formThis command scaffolds a new Next.js project with TypeScript support, providing a robust foundation for our form.
Creating the Contact Form Component
We’ll create a ContactForm component in components/ContactForm.tsx. This component will be the user interface for our contact form.
import { useState } from 'react';
const ContactForm: React.FC = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// Here we will implement a secure submission
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" value={formData.name} onChange={handleChange} placeholder="Your Name" required />
<input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Your Email" required />
<textarea name="message" value={formData.message} onChange={handleChange} placeholder="Your Message" required />
<button type="submit">Send</button>
</form>
);
};
export default ContactForm;Adding Validation and Anti-Spam Measures
Input Validation
To prevent malicious data from being submitted, always validate inputs both on the client-side and server-side.
const validateEmail = (email: string): boolean => {
const re = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
return re.test(email);
};
// Call validateEmail in handleSubmit to verify email formatCaptcha Integration
CAPTCHAs deter automated submissions. Google’s reCAPTCHA is a popular choice and can be easily integrated.
npm install react-google-recaptchaIn your component:
import ReCAPTCHA from 'react-google-recaptcha';
// Add the following inside your form
<ReCAPTCHA sitekey="your-recaptcha-site-key" onChange={handleCaptchaChange} />
const handleCaptchaChange = (captchaValue: string | null) => {
// Use captchaValue to verify CAPTCHA on the server
};Secure Data Handling on Server Side
Implement an API route in Next.js to handle form submissions securely.
Get @rnab’s stories in your inbox
Join Medium for free to get updates from this writer.
Create pages/api/contact.ts:
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const { name, email, message } = req.body;
// Validate input
if (!validateEmail(email)) {
return res.status(400).json({ error: 'Invalid email' });
}
// Implement CAPTCHA and other checks
// Save data to a database or send an email notification
res.status(200).json({ message: 'Message received' });
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}Conclusion
Ensuring security in contact forms is a balance of user experience and technical safeguards. With Next.js and TypeScript, you can build efficient and secure forms by maintaining code quality and user trust. Future enhancements can include rate limiting, advanced bot detection, and integration with third-party services for email notifications. By implementing these practices, you’ll be well-prepared to handle user communications securely.





