Written by: Geoffrey Callaghan
Create a Contact Form with Next.js Server Actions
Create A Contact Form With Next.Js Server Actions
To create a contact form with Next.js Server Actions, you’ll use Next.js API routes to handle form submissions on the server-side. Here’s a step-by-step guide to creating a contact form with Next.js Server Actions:
If you haven’t already set up a Next.js project, you can create one using the following command:
npx create-next-app my-nextjs-app
cd my-nextjs-app
Create a new file named ContactForm.js
in the components
directory:
// components/ContactForm.js
import { useState } from 'react';
const ContactForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
message: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (res.ok) {
console.log('Message sent successfully!');
// Optionally reset form fields
setFormData({ name: '', email: '', message: '' });
} else {
console.error('Failed to send message');
}
} catch (error) {
console.error('Error sending message:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" name="name" value={formData.name} onChange={handleChange} required />
</div>
<div>
<label htmlFor="email">Email:</label>
<input type="email" id="email" name="email" value={formData.email} onChange={handleChange} required />
</div>
<div>
<label htmlFor="message">Message:</label>
<textarea id="message" name="message" value={formData.message} onChange={handleChange} required />
</div>
<button type="submit">Send</button>
</form>
);
};
export default ContactForm;
Create a new file named contact.js
in the pages/api
directory:
// pages/api/contact.js
export default async function handler(req, res) {
if (req.method === 'POST') {
const { name, email, message } = req.body;
// Example: Send email using a third-party service
try {
// Code to send email
console.log(`Message received from ${name} <${email}>: ${message}`);
res.status(200).json({ message: 'Message sent successfully' });
} catch (error) {
console.error('Error sending message:', error);
res.status(500).json({ message: 'Failed to send message' });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
You can now use the ContactForm
component wherever you need the contact form in your Next.js application:
// pages/index.js
import ContactForm from '../components/ContactForm';
export default function Home() {
return (
<div>
<h1>Contact Us</h1>
<ContactForm />
</div>
);
}
Start your Next.js application:
npm run dev
Now, when you submit the contact form, it will send a POST request to the /api/contact
endpoint, where you can handle the form submission on the server-side. This approach allows you to perform server-side processing, such as sending emails or saving form data to a database, securely within your Next.js application.