Forms enable you to create and update data in web applications. Next.js provides a powerful way to handle form submissions and data mutations using API Routes.
Good to know
We will soon recommend incrementally adopting the App Router and using Server Actions for handling form submissions and data mutations. Server Actions allow you to define asynchronous server functions that can be called directly from your components, without needing to manually create an API Route.
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.
With the Pages Router, you need to manually create API endpoints to handle securely mutating data on the server.
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 { FormEvent } from 'react'export default function Page() { async function onSubmit(event: FormEvent<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> )}
You can set cookies inside an API Route using the setHeader method on the response:
TypeScript
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'export default async function handler( req: NextApiRequest, res: NextApiResponse) { res.setHeader('Set-Cookie', 'username=lee; Path=/; HttpOnly') res.status(200).send('Cookie has been set.')}