Server-side Form Submission in Next.js
Create an example of handling a form submission on the server side in Next.js using API routes and providing feedback to the user on success or failure.
export default function ContactPage() {
// Handler for form submission
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const body = JSON.stringify(Object.fromEntries(formData));
try {
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
});
if (response.ok) {
// Handle success
alert('Form successfully submitted!');
} else {
throw new Error('Form submission failed!');
}
} catch (error) {
// Handle error
alert(error.message);
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" required />
<input type="email" name="email" required />
<textarea name="message" required></textarea>
<button type="submit">Submit</button>
</form>
);
}
This is a React component in Next.js for rendering and handling a contact form submission. It captures form data on submit, converts it to JSON, and sends it to a server-side API route using 'fetch'. Upon successful response, it alerts the user of the success, and in case of an error, it alerts the user of the failure.
export default async function handler(req, res) {
if (req.method === 'POST') {
try {
const { name, email, message } = req.body;
// Here you would typically handle the form data, e.g., store in a database
// For this example, we're just sending a response that it's successful
// Send a success response
res.status(200).json({ message: 'Form submitted successfully!' });
} catch (error) {
// Send an error response if something goes wrong
res.status(500).json({ error: 'Failed to submit form' });
}
} else {
// Handle any other HTTP methods
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
This is the API route handler '/api/contact' for handling the form submission. It checks for a POST request, and if valid, processes the form data. This is where the form handling logic such as database integration would be added. On successful processing, it sends a success response back to the client. If there's an error, or if the request method is not POST, it sends the appropriate error response.