Forms enable you to create and update data in web applications. Next.js provides a powerful way to handle data mutations using API Routes. This guide will walk you through how to handle form submission on the server.
To handle form submissions on the server, create an API endpoint that securely mutates data.
TypeScript
pages/api/submit.ts
import type { NextApiRequest, NextApiResponse } from 'next'export default async function handler( req: NextApiRequest, res: NextApiResponse) { const data = req.body const id = await createItem(data) res.status(200).json({ id })}
Then, call the API Route from the client with an event handler:
TypeScript
pages/index.tsx
import { SubmitEvent } from 'react'export default function Page() { async function onSubmit(event: SubmitEvent<HTMLFormElement>) { event.preventDefault() const formData = new FormData(event.currentTarget) const response = await fetch('/api/submit', { method: 'POST', body: formData, }) // Handle response if necessary const data = await response.json() // ... } return ( <form onSubmit={onSubmit}> <input type="text" name="name" /> <button type="submit">Submit</button> </form> )}
Since API Routes run on the server, we're able to use sensitive values (like API keys) through Environment Variables without exposing them to the client. This is critical for the security of your application.
We recommend using HTML validation like required and type="email" for basic client-side form validation.
For more advanced server-side validation, you can use a schema validation library like Zod or Valibot to validate the form fields before mutating the data:
TypeScript
pages/api/submit.ts
import type { NextApiRequest, NextApiResponse } from 'next'import { z } from 'zod'const schema = z.object({ // ...})export default async function handler( req: NextApiRequest, res: NextApiResponse) { const parsed = schema.parse(req.body) // ...}