Build a Simple Next.js Interactive Web-Based Feedback Form

Written by

in

In the digital age, gathering feedback is crucial for understanding your users and improving your product or service. Whether you’re a small business owner, a blogger, or a developer, collecting user opinions can provide invaluable insights. This tutorial will guide you through building a simple, yet effective, interactive feedback form using Next.js. We’ll cover everything from setting up the project to handling form submissions, making it easy for beginners to get started and intermediate developers to refine their skills. By the end of this guide, you’ll have a fully functional feedback form that you can integrate into any Next.js project.

Why Build a Feedback Form with Next.js?

Next.js offers several advantages for building web applications, including:

  • Server-Side Rendering (SSR) and Static Site Generation (SSG): Improve SEO and initial load times.
  • Built-in Routing: Simplifies navigation and page management.
  • API Routes: Easily create backend endpoints for handling form submissions.
  • Developer Experience: Fast refresh, TypeScript support, and a great community.

Building a feedback form with Next.js allows you to create a performant, SEO-friendly, and user-friendly experience for your visitors. It also provides a robust and scalable foundation for future enhancements.

Prerequisites

Before we begin, ensure you have the following installed:

  • Node.js and npm (or yarn): Required for managing project dependencies and running the development server.
  • A Code Editor: Such as Visual Studio Code, Sublime Text, or Atom.
  • Basic Knowledge of HTML, CSS, and JavaScript: Familiarity with these languages is essential for understanding the code.

Setting Up the Next.js Project

Let’s start by creating a new Next.js project. Open your terminal and run the following command:

npx create-next-app feedback-form-app

This command will create a new directory called feedback-form-app and set up a basic Next.js project structure for you. Navigate into the project directory:

cd feedback-form-app

Now, install any necessary dependencies. For this project, we won’t need any external libraries, but it’s good practice to update your dependencies:

npm install

Creating the Feedback Form Component

We’ll create a reusable component for our feedback form. This will keep our code organized and make it easier to maintain. Create a new file named FeedbackForm.js in the components directory (you’ll need to create this directory if it doesn’t exist):

// components/FeedbackForm.js
import { useState } from 'react';

function FeedbackForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [feedback, setFeedback] = useState('');
  const [submitted, setSubmitted] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const data = {
      name,
      email,
      feedback,
    };

    try {
      const response = await fetch('/api/feedback', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });

      if (response.ok) {
        setSubmitted(true);
        setName('');
        setEmail('');
        setFeedback('');
      } else {
        console.error('Failed to submit feedback');
        // Handle error (e.g., display an error message to the user)
      }
    } catch (error) {
      console.error('Error submitting feedback:', error);
      // Handle error
    }
  };

  if (submitted) {
    return (
      <div>
        <p>Thank you for your feedback!</p>
      </div>
    );
  }

  return (
    
      <div>
        <label>Name:</label>
         setName(e.target.value)}
          required
        />
      </div>
      <div>
        <label>Email:</label>
         setEmail(e.target.value)}
          required
        />
      </div>
      <div>
        <label>Feedback:</label>
        <textarea id="feedback"> setFeedback(e.target.value)}
          required
        />
      </div>
      <button type="submit">Submit Feedback</button>
      {`
        .feedback-form {
          display: flex;
          flex-direction: column;
          max-width: 400px;
          margin: 0 auto;
          padding: 20px;
          border: 1px solid #ccc;
          border-radius: 5px;
        }

        .feedback-form div {
          margin-bottom: 15px;
        }

        .feedback-form label {
          display: block;
          margin-bottom: 5px;
          font-weight: bold;
        }

        .feedback-form input[type="text"],  .feedback-form input[type="email"], .feedback-form textarea {
          width: 100%;
          padding: 10px;
          border: 1px solid #ccc;
          border-radius: 4px;
          font-size: 16px;
        }

        .feedback-form textarea {
          height: 150px;
        }

        .feedback-form button {
          background-color: #4CAF50;
          color: white;
          padding: 12px 20px;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 16px;
        }

        .feedback-form button:hover {
          background-color: #45a049;
        }
      `}
    
  );
}

export default FeedbackForm;

Let’s break down this component:

  • State Variables: name, email, feedback, and submitted are managed using the useState hook.
  • Input Fields: The form includes input fields for name, email, and a textarea for feedback.
  • Event Handlers: onChange events update the state variables as the user types.
  • handleSubmit Function: This function is called when the form is submitted. It prevents the default form submission behavior, prepares the data, and sends a POST request to our API route (we’ll create this next). If the submission is successful, it sets submitted to true, and clears the form fields.
  • Conditional Rendering: The component displays a “Thank you” message after successful submission.
  • Styling: The <style jsx> block provides basic styling for the form.

Creating the API Route to Handle Form Submissions

Next.js makes it easy to create API routes. These routes handle the backend logic for our feedback form. Create a new file named feedback.js in the pages/api directory:

// pages/api/feedback.js
export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { name, email, feedback } = req.body;

    // Validate the input (you should add more robust validation)
    if (!name || !email || !feedback) {
      return res.status(400).json({ error: 'All fields are required' });
    }

    // In a real application, you would save this data to a database
    // For this example, we'll just log it to the console
    console.log('Feedback received:', { name, email, feedback });

    // Simulate saving to a database by pausing for 1 second.
    await new Promise(resolve => setTimeout(resolve, 1000));

    res.status(200).json({ message: 'Feedback received successfully!' });
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

Here’s what the API route does:

  • Method Handling: It checks if the request method is POST. If not, it returns a 405 error (Method Not Allowed).
  • Data Extraction: It extracts the name, email, and feedback from the request body.
  • Input Validation: Basic validation is performed to ensure all fields are provided.
  • Data Handling: In a real-world scenario, you’d save the data to a database. For this example, the data is logged to the console. Added a 1 second delay to simulate a database operation.
  • Response: It returns a 200 status code with a success message if the feedback is received successfully, and a 400 if validation fails.

Integrating the Feedback Form into a Page

Now, let’s integrate the FeedbackForm component into a page. Open pages/index.js and modify it as follows:

// pages/index.js
import FeedbackForm from '../components/FeedbackForm';

function Home() {
  return (
    <div>
      <h1>Feedback Form</h1>
      <p>Please share your thoughts:</p>
      
    </div>
  );
}

export default Home;

This imports the FeedbackForm component and renders it on the home page. Now, run your development server:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see the feedback form.

Testing the Feedback Form

Fill out the form with your name, email, and feedback, and click the “Submit Feedback” button. If everything is set up correctly, you should see the “Thank you” message. Also, check your terminal’s console to see the feedback data logged by the API route.

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • CORS (Cross-Origin Resource Sharing) Errors: If you encounter CORS errors, ensure your API route is correctly configured. For local development, you might not need to worry, but for production, you’ll likely need to configure CORS headers.
  • Incorrect API Route Path: Double-check the path in your fetch request within the FeedbackForm.js component. It should match the file path of your API route (/api/feedback in this case).
  • Missing Dependencies: Ensure you’ve installed all the necessary dependencies (although for this project, no external dependencies are strictly needed).
  • Incorrect Form Handling: Make sure you’re using e.preventDefault() in the handleSubmit function to prevent the default form submission behavior.
  • Server-Side Errors: Check your server-side logs (the terminal where you ran npm run dev) for any errors that might occur during the API request.
  • Typographical Errors: Carefully check your code for any typos, especially in variable names and component names.

Enhancements and Next Steps

Here are some ideas for enhancing your feedback form:

  • Add Input Validation: Implement more robust input validation on both the client and server sides to ensure data integrity.
  • Implement Email Notifications: Send email notifications to yourself or a designated recipient whenever a new feedback submission is received.
  • Integrate with a Database: Store the feedback data in a database (e.g., MongoDB, PostgreSQL) for persistent storage and easier management.
  • Implement Rate Limiting: Prevent abuse by implementing rate limiting on your API route.
  • Add Rich Text Editor: Allow users to format their feedback using a rich text editor.
  • Use a Third-Party Service: Consider using a third-party service like Formspree or Netlify Forms for handling form submissions without writing your own backend.

Summary / Key Takeaways

In this tutorial, we’ve built a simple, interactive feedback form using Next.js. We’ve covered the essential steps, from setting up the project and creating the form component to handling form submissions with an API route. You’ve learned how to handle user input, make API requests, and display feedback confirmation. Remember to always validate user input and handle potential errors gracefully. By following this guide, you should now have a solid understanding of how to create feedback forms with Next.js and integrate them into your projects. The ability to collect and analyze user feedback is crucial for any project’s success, and this form provides a foundation upon which you can build more sophisticated and feature-rich feedback systems. Don’t hesitate to experiment with the enhancements suggested, and adapt the form to meet the specific needs of your project.

FAQ

Q: How do I deploy this feedback form?

A: You can deploy your Next.js application to various platforms like Vercel (recommended, as it’s built by the Next.js team), Netlify, or AWS. The deployment process generally involves pushing your code to a repository (like GitHub) and connecting it to your chosen deployment platform. The platform will then build and deploy your application.

Q: How can I prevent spam submissions?

A: Implement measures like CAPTCHA, rate limiting, and server-side validation to prevent spam. Consider using a service like reCAPTCHA or hCaptcha to verify user interactions.

Q: How do I style the form more effectively?

A: You can use CSS modules, styled-components, or a CSS framework like Tailwind CSS for more advanced styling. Use the className attribute to apply styles to your form elements.

Q: Can I use this form with a database?

A: Yes! Modify the API route to connect to a database (like MongoDB, PostgreSQL, or others). You’ll need a database client library for your chosen database and configure the necessary connection details.

Q: How can I send email notifications when a form is submitted?

A: In your API route, after successfully saving the feedback, use a library like Nodemailer to send an email. You’ll need to configure the email server details (SMTP) in your code or environment variables.

Building this feedback form is a practical step towards understanding how to gather user insights and improve your applications. Remember, the key to success lies in iterating and refining your approach based on feedback and real-world usage. As you continue to build and deploy, consider the user experience and iterate on the form based on the data you receive. Continuous improvement is the cornerstone of any successful project, and incorporating feedback effectively is a vital step in that journey.