Building Serverless Forms with Netlify Functions

Forms are a crucial element in many software applications, allowing users to input data that can be processed and stored. With the rise of JAMStack technologies and serverless approaches, it’s now possible to handle form data without relying on a traditional backend. In this article, we’ll explore how to build fully serverless forms using Netlify Lambda functions.

What is a Serverless Function?

A serverless function is a piece of code that can be executed on demand, without the need for a dedicated server. This approach allows for greater scalability and flexibility, as computing resources are only utilized when needed. Serverless functions can be used to process form data, interact with databases, and perform other tasks.

Project Setup

To get started, we’ll create a new Next.js project and install the necessary dependencies. We’ll use React Hook Form for client-side form validation, Yup for schema validation, and TailwindCSS for styling.

bash
npx create-next-app my-app
cd my-app
npm install react-hook-form yup tailwindcss

Defining the Form Schema

Next, we’ll define the schema for our form using Yup. This will help us validate user input and ensure that it conforms to our expected format.

“`javascript
import * as yup from ‘yup’;

const formSchema = yup.object().shape({
fullName: yup.string().required(),
companyEmail: yup.string().email().required(),
phoneNumber: yup.string().min(7).max(12),
companyWebsite: yup.string().url(),
companySize: yup.number().required(),
acceptTerms: yup.boolean().required(),
});
“`

Creating the Form

Now that we have our schema defined, we can create the form itself. We’ll use React Hook Form to handle form state and validation.

“`javascript
import { useForm } from ‘react-hook-form’;
import { formSchema } from ‘../schema’;

function MyForm() {
const { register, handleSubmit, errors } = useForm({
validationSchema: formSchema,
});

const onSubmit = async (data) => {
// Process form data here
};

return (

Full Name:

{errors.fullName &&

{errors.fullName.message}

}


{errors.companyEmail &&

{errors.companyEmail.message}

}
{/* … */}

);
}
“`

Connecting to a Database

To store our form data, we’ll need to connect to a database. We’ll use MongoDB Atlas for this example.

“`javascript
import mongoose from ‘mongoose’;

const dbUrl = ‘mongodb+srv://username:[email protected]/database-name’;

mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on(‘error’, console.error.bind(console, ‘connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});
“`

Creating a Netlify Function

Finally, we’ll create a Netlify function to process our form data. This function will be triggered when the form is submitted.

“`javascript
import { Handler } from ‘@netlify/functions’;
import { db } from ‘../db’;

const handler: Handler = async (event) => {
const data = JSON.parse(event.body);
const collection = db.collection(‘forms’);
await collection.insertOne(data);
return {
statusCode: 200,
body: JSON.stringify({ message: ‘Form submitted successfully’ }),
};
};

export { handler };
“`

Deploying the Function

To deploy our function, we’ll need to create a netlify.toml file and configure our Netlify site.

toml
[functions]
directory = "functions"

We’ll also need to update our next.config.js file to include the Netlify function.

javascript
module.exports = {
// ...
target: 'serverless',
// ...
};

That’s it! We’ve now created a fully serverless form using Netlify Lambda functions. When the form is submitted, our function will be triggered, processing the form data and storing it in our MongoDB database.

Leave a Reply

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