Netlify Forms not working with Next.js website

45 Views Asked by At

I’m trying to use netlify forms with my Next.js website but it doesn't work, I don’t get how to do it. Please help!

Here's my code.

<form className='contacts-form' onSubmit={handleSubmit} method='post' name="contact" data-netlify="true">
    <input type="hidden" name="form-name" value="contact" />
    {/* other inputs... */}
    <button type="submit" name="submit">Submit</button>
</form>
  const handleSubmit = (event) => {
    event.preventDefault();
  
    const myForm = event.target;
    const formData = new FormData(myForm);
  
    fetch("/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams(formData).toString(),
    })
      .then(() => router.push("/thank-you"))
      .catch((error) => alert(error));
  };
1

There are 1 best solutions below

0
fonzie123 On

I solved my issue.

I had an error 303 due to the redirect of my app. I solved it by editing my handleSubmit function: Instead of

fetch("/", {...

I changed it to:

fetch(`/${locale}`, {...

because previously I had

import { useRouter } from 'next/router';
// other code...
const router = useRouter();
const { locale } = router;

!!!You need a form.html to help netlify detect your form!!! You have to put it in the public folder:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Netlify form</title>
</head>

<body>
    <!-- A little help for the Netlify post-processing bots -->
    <form name="contactform" data-netlify="true" hidden>
        <label for="nome">Nome:</label>
        <input id="nome" type="text" name="nome" />

        <label for="cognome">Cognome:</label>
        <input id="cognome" type="text" name="cognome" />

        <label for="email">Email:</label>
        <input id="email" type="email" name="email" />

        <label for="messaggio">Messaggio:</label>
        <textarea id="messaggio" name="messaggio"></textarea>

        <button type="submit" name='submit'></button>

    </form>
</body>

</html>

Note that if labels are empty, Netlify will not send the content of the input to the email notification. It will only be shown in the Netlify UI.