Server Actions in Next.js

Setting Up the Form Component

'use client';

import React, { useState } from 'react';

export default function ContactForm() {
 const [message, setMessage] = useState('');

 async function handleSubmit(event) {
  event.preventDefault();

  const formData = new FormData(event.target);
  const response = await fetch('/api/contact', {
   method: 'POST',
   body: formData,
  });

  const result = await response.json();
  setMessage(result.message);
 }

 return (
  <form onSubmit={handleSubmit}>
   <input type="text" name="name" placeholder="Your Name" required />
   <input type="email" name="email" placeholder="Your Email" required />
   <textarea name="message" placeholder="Your Message" required></textarea>
   <button type="submit">Send Message</button>
   {message && <p>{message}</p>}
  </form>
 );
}

Creating the Server Action

Next, create a server-side function to handle the form data. This function will reside in the pages/api directory and act as an API endpoint for the form submission:

// pages/api/contact.js


export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { name, email, message } = req.body;


    // Perform server-side operations here (e.g., save to a database, send an email, etc.)


    res.status(200).json({ message: 'Your message has been sent!' });
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

Client Component (ContactForm): Handles form input and submits the form data to the server using the Fetch API.

Server Action (handler function in pages/api/contact.js): Processes the form data on the server side. It responds with a JSON object indicating whether the operation was successful.

Leave a comment

Your email address will not be published. Required fields are marked *