Building a Form and Email Notification System with Directus and Next.js
Tags: nextjs, directus, api
Published: 2023-08-09 15:13:00

---
title: Building a Form and Email Notification System with Directus and Next.js
published: true
description: Learn how to use Directus as a composable data platform that stores form data and sends instant email notifications.
tags: nextjs, directus, api
cover_image: "https://marketing.directus.app/assets/69fb6d14-3fc6-457a-8976-0a167814465f.png"
canonical_url: "https://docs.directus.io/blog/building-a-form-data-collection-and-email-notification-system-with-directus-and-next-js"
---

Well-designed data collection and notification processes empower businesses to gather key information about their customers in an efficient and actionable manner.

In this tutorial, we will walk through how to use Directus as a composable data platform that stores form data and sends instant email notifications.

Here’s a quick overview of the system:
- Users complete a form in a Next.js app
- Directus stores the submitted information in a collection
- When a new submission is stored, an automated workflow is triggered in Directus to send an email notification to the business and a thank you email to the user


## Prerequisites
To follow along with this tutorial, it is important to have the following:
1. A Directus project, either self-hosted or a [Cloud account](https://directus.cloud/login).
2. Basic knowledge of React.js and Next.js.


## Setting up a Directus Collection for Data Storage
To begin, log in to your Directus app and navigate to **Settings** > **Data Model**

Click the + icon to create a new collection called “**user_data**”.

![Create New Collection](https://marketing.directus.app/assets/4ca7789e-ce0f-4453-aee1-58dabfcfc47c.png)

Add the following fields to the "**user_data**" collection and save:
- **full_name (Type: String, Interface: Input)**: To capture the user's full name.
- **email_address (Type: String, Interface: Input)**: To store the user's email address.
- **phone_number (Type: String, Interface: Input)**: To store the user's phone number.
- **country (Type: String, Interface: Input)**: Implement a field to record the user's country.
- **about_you (Type: Text, Interface: Textarea)**: To collect additional information from users, such as their interests or feedback.

![User Data Collection Fields](https://marketing.directus.app/assets/820c6951-88c8-4db5-b3ed-d2a2dc18a2b8.png)

### Enabling Public Access for the Collection
To enable open access to the data stored within this collection, we need to give it public access.
Head over to **Settings** > **Roles & Permission**

Navigate to the public role and then toggle Create permission from “No Access” to “All Access”.

![User Data Collection Fields](https://marketing.directus.app/assets/775596e8-702d-4c9f-bca1-2416e102f32d.png)

This setting ensures that the data stored in the collection is easily accessed without authentication.

Now that the collection is in place, it's time to proceed with building the frontend of our application using Next.js.

## Creating the Next.js Application
Install Next.js by running this command:

```
npx create-next-app@latest form-email-app

```

Once the installation is complete, proceed to the newly created directory:

```
cd form-email-app
```

Proceed to install dependencies and run the scaffolded Next.js application with the command:

```
npm run dev
```

Now, open http://localhost:3000/ on your browser, and you should see the Next.js starter page


![Next.js Starter Page](https://marketing.directus.app/assets/578785e3-7b2c-42d5-8b5a-d7c3e4a3aaca.png)


> This project uses the Next.js App directory. 

Back in the code editor, enable [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions) in Next.js, by updating the next.config file.


```js
const nextConfig = {
  experimental: {
    serverActions: true,
  },
};
```

## Building the form component to capture user data
Go over to the `page.js` file. We’ll do some cleanup here.

First, remove the placeholder code and create a form component with the following fields:
- Full Name
- Email Address
- Phone Number
- Country
- About You

Your code should look like this:

```jsx
export default function Home() {
  // handleSubmit function to be here

return (
    <main>
      <form action={handleSubmit}>
        <h1>User Data Form</h1>
        <p>Please fill in your details below</p>
        <div className='form-flex'>
          <label htmlFor='name'>Full Name</label>
          <input id='name' name='full_name' required />
        </div>
        <div className='form-flex'>
          <label htmlFor='email'>Email Address</label>
          <input type='email' name='email_address' id='email' required />
        </div>
        <div className='form-flex'>
          <label htmlFor='phone'>Phone Number</label>
          <input type='tel' name='phone_number' id='phone' required />
        </div>
        <div className='form-flex'>
          <label htmlFor='country'>Choose your Country</label>
          <select name='country' id='country' required>
            <option value='kenya'>Kenya</option>
            <option value='usa'>United States</option>
            <option value='germany'>Germany</option>
            <option value='uae'>United Arab Emirates</option>
          </select>
        </div>
        <div className='form-flex'>
          <label htmlFor='aboutyou'>About You</label>
          <textarea
            id='aboutyou'
            name='about_you'
            rows='4'
            cols='50'
            required
            placeholder='Enter information about yourself...'
          />
        </div>
        <button type='submit'>Submit</button>
      </form>
    </main>
  );
}
```


## Integrating the Directus SDK with Next.js
Install the SDK using the command:

```
npm install @directus/sdk
```

Import the required composables at the top of your file:

```
import { createDirectus, rest, createItem } from "@directus/sdk"
```

Now, create a composable client with REST support

```
const client = createDirectus('<http://directus.example.com>').with(rest());
```

> 💡 Remember to change the http://directus.example.com URL to your actual URL.


Now, we need to set up the `handleSubmit` function that sends data using the Directus SDK

```
 const handleSubmit = async (formData) => {
    'use server';

    const full_name = formData.get('full_name');
    const email_address = formData.get('email_address');
    const phone_number = formData.get('phone_number');
    const country = formData.get('country');
    const about_you = formData.get('about_you');

    try {
      await client.request(
        createItem('user_data', {
          full_name,
          email_address,
          phone_number,
          country,
          about_you,
        })
      );
    } catch (error) {
      console.log(error);
    }
  };
```

Whenever a user completes the form, the data is sent to the collection.

## Configuring the Email Notification Flow
Directus Flows enable you to create automation to streamline various processes within your Directus project.

![Creating a Flow in Directus](https://marketing.directus.app/assets/15ea1903-f554-4f92-bd5d-1fc764a4dab7.png)

To set up a flow, go to **Settings** > **Flows**

Click the **+** icon to create a new flow called “**Data Email Flow**” and add a description.

Next, we need to set up a trigger for our flow. Triggers are events that initiate a workflow.

For this flow, choose the following options:
- **Trigger**: Select the event hook as the trigger.
- **Action**: The action we'll take is non-blocking, meaning it won't cause delays in the process.
- **Scope**: The scope of this flow is focused on `items.create`.
- **Collection**: We'll be working with the `user_data` collection.


## Adding Operations to the Flow

Operations are specific tasks to be carried out in response to the trigger event in a flow.

Add the first operation, which is to send an email notification to you as the administrator.

Edit the flow to create an operation called "**Email Notification to Me**"

![Adding an operation to a Flow in Directus](https://marketing.directus.app/assets/26ba9903-ccc0-4339-af0a-5ed6cb4f27e8.png)

Now, select **Send Email** and fill in the email address the notification is to be sent to and the subject of the email.

Keep the type of the body as **Markdown** but feel free to explore other types.

![Creating an operation in Directus](https://marketing.directus.app/assets/35e6a851-6eb2-44ff-b9ea-48d4eb4afd2e.png)

Since you have the email of the user, you can customize the email body with the name of the user with <span v-pre>`{{$trigger.payload.full_name}}`.</span>

![Sample Body for Email Notification Flow](https://marketing.directus.app/assets/5fa91ff1-c94a-47f9-a497-aabff911191d.png)


Now, save the flow.

Whenever your form is completed, you'll get an email notification.

That's not all! Additionally, you need to send follow-up emails to users as a gesture of appreciation for completing the form and even offer an incentive.

To achieve this, include an additional operation in our flow similar to the one above.

## Setting up the operation to send emails to users

Head over to your flow and edit it.

Include an additional operation for sending an email following the previously mentioned steps. 
However, this time, make the receiver email dynamic, adapting its value to the information filled out by the user using <span v-pre>`{{$trigger.payload.email_address}}`.</span>

![Thank You Email Notification Flow](https://marketing.directus.app/assets/127c2160-e01a-4d00-9359-a6cb038098b6.png)

Complete the rest of the fields and save your flow.


<details>
  <summary>Toggle open to see a sample email body</summary>
  
  ```
 Hi {{$trigger.payload.full_name}},

 Your feedback has been received and much appreciated.

 Use this coupon code on your next checkout: "PRO11".

 Till next time,

 Thanks.
  ```

  </details>
  
 Now go ahead and test your entire application by completing the user data form. You'll get an instant notification in your email. The user will also receive the thank you email.

## Conclusion
You’ve just learnt how to set up the data collection process and implement an email notification system using Directus.

Further enhance and customize this application to suit your project needs by:
- **Implementing Real-Time Updates**: Add real-time to get the most up-to-date data instantly.
- **Enabling User Permissions and Roles**: This helps to control data access and security
- **Utilizing Insights**: Directus Insights allow you to visualize data and gain more knowledge from your collected data.

If you have any questions or need further assistance, please feel free to drop by our [Discord server](https://directus.chat/).