NextJS TypeScript Form

Receive submissions emails, get notifications, sync to your CRM/database.

This guide will show you how to make a nice-looking and elegant form with NextJS, Tailwind CSS, and TypeScript. It works perfectly with standard NextJS pages and the new app directory, but can be used on standalone React too.

On top of that, your form will be able to handle spam submissions, send emails, and sync with your CRM/database.

For react/plain javascript, check out the react contact form guide.

Create the NextJS app

(if you're starting a brand new project, otherwise you can skip it)

In case you're starting a brand new project, you'll need some initial steps. One of the most straightforward ways is to use the create-next-app package. To start:

  • Open the terminal and go to the directory where you will store your project. For example
    mkdir ~/nextjs-project && cd ~/nextjs-project
  • Then create your app in this folder; this will be your project root folder
    npx create-next-app@latest .
  • The following tutorial will assume you'll answer all questions with "yes". This means you'll have TypeScript, EsLint, Tailwind CSS, `src/` directory, experimental `app/` directory and import alias "@/".
    NextJS setup
  • When the installation has finished, you can start the server
    npm run dev

Use your favorite code editor to work with files in ~/nextjs-project. You will be able to make a contact form there.

Create the contact form component

Create a new file called ContactForm.tsx in the src/components/ folder. You can copy-paste the code below to get started quickly. Check HeroTofu's extensive forms library for other ready to use forms.

function ContactForm() {
  return (
    <div className="md:w-96 md:max-w-full w-full mx-auto">
      <div className="sm:rounded-md p-6 border border-gray-300">
        <form method="POST" action={FORM_ENDPOINT}>
          <label className="block mb-6">
            <span className="text-gray-700">Your name</span>
            <input
              type="text"
              name="name"
              className=" focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block w-full mt-1 border-gray-300 rounded-md shadow-sm"
              placeholder="Joe Bloggs"
            />
          </label>
          <label className="block mb-6">
            <span className="text-gray-700">Email address</span>
            <input
              name="email"
              type="email"
              className=" focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block w-full mt-1 border-gray-300 rounded-md shadow-sm"
              placeholder="joe.bloggs@example.com"
              required
            />
          </label>
          <label className="block mb-6">
            <span className="text-gray-700">Message</span>
            <textarea
              name="message"
              className=" focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block w-full mt-1 border-gray-300 rounded-md shadow-sm"
              rows={3}
              placeholder="Tell us what you're thinking about..."
            ></textarea>
          </label>
          <div className="mb-2">
            <button
              type="submit"
              className=" focus:shadow-outline hover:bg-indigo-800 h-10 px-5 text-indigo-100 transition-colors duration-150 bg-indigo-700 rounded-lg"
            >
              Contact Us
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default ContactForm;

Use the form hook to handle submissions

To effortlessly handle form submissions, you can use the herotofu-react package. It will do all the form submission process work for you.

npm install --save herotofu-react

Then, adjust the Form component to use the hook with new `formState` and `getFormSubmitHandler`.

function ContactForm() {
  // TODO - update to the correct endpoint
  const { formState, getFormSubmitHandler } = useFormData('https://herotofu.com/start');

  const onSubmitCallback = ({ status, data }) => {
    // Sync the success/error status with 3rd party services easily. For example, analytics or CRM
    console.log(`The form finished submission in status: ${status} and data: ${JSON.stringify(data)}`);
  };

  const statusBg =
    formState.status === 'not_initialized'
      ? ''
      : formState.status === 'error'
        ? 'bg-red-600 text-red-100'
        : formState.status === 'loading'
          ? 'bg-yellow-600 text-yellow-100'
          : 'bg-green-600 text-green-100';

  return (
    <div className="md:w-96 md:max-w-full w-full mx-auto">
      <div className="sm:rounded-md p-6 border border-gray-300">
        {!!formState.status && (
          <div className={`mb-4 py-2 ${statusBg}`}>
            Current form status is: {formState.status}
            {formState.status === 'error' && <> {formState.error.message}</>}
          </div>
        )}
        <form onSubmit={getFormSubmitHandler(onSubmitCallback, injectedData)}>

  // Here goes the rest of the code...

Embed form into your app

Open any page you want to see the form and insert the newly created form component. It will work for old pages and the new app directory (don't forget the "use client" directive if using app directory).

import ContactForm from '../components/ContactForm';

function Page() {
  return <ContactForm />;
}

export default Page;

Create the free HeroTofu forms backend

Head over to herotofu.com and create an account. It will handle all the boring and complex form submission process work for you. You'll get 14 days of the free trial at first, and later you can leave it with the free forever plan. For vast majority of people, free plan is usually more than enough.

HeroTofu registration is straightforward. Fill in the basic fields and then confirm your email address.

Herotofu signup

Once you have confirmed your email address, go to app.herotofu.com/forms to create your first form. Fill in the form name and add your preferred email address where you'd like to receive your form submits. Slack and Zapier are also options, but you need to pay for them once the trial is over.

You'll get the form endpoint URL once you hit submit, so remember to copy it.

Herotofu Forms List

Use the created forms backend in your contact form

Once again, open the ContactForm.js file and fill in the form endpoint URL. You need to change the passed string to the useFormData() at the top of the component. It should look like this.

import { useFormData } from 'herotofu-react';

const ContactForm = () => {
  const { formState, getFormSubmitHandler } = useFormData('EXAMPLE_FORM_ID');

  // The rest of the code...

Done! Go ahead and test your form submission! You don't need to do any backend email work, as HeroTofu will handle everything.

Bonus: it's not only a forms endpoint

HeroTofu accepts regular form submissions, multipart file uploads, and JSON payloads. So you can create javascript objects and send them via fetch() to the endpoint. When you send a JSON payload, don't forget to set the correct JSON headers, and HeroTofu will respond with the needed status codes. Here's what it could look like in practice.

// the regular useFormData is for forms
// useJsonData is a helper hook that sends JSON payloads to HeroTofu
// however, it uses the same form endpoint
import { useJsonData } from 'herotofu-react';

function useEmailSubscribe() {
  const { dataState: subscribeState, sendData } = useJsonData(HEROTOFU_FORM_ID);

  const subscribe = (emailToSubsribe: string) => {
    const email = String(emailToSubsribe).trim();
    sendData(undefined, { email });
  };

  return { subscribeState, subscribe };
}

export default useEmailSubscribe;

Treat it as a REST API because as long as you're sending POST, you'll be good to go. Your react form submission will reach your inbox.