Forms and Mutations
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.
- API Routes do not specify CORS headers, meaning they are same-origin only by default.
- 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.
Examples
Redirecting
If you would like to redirect the user to a different route after a mutation, you can redirect
to any absolute or relative URL:
pages/api/submit.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}
Setting cookies
You can set cookies inside an API Route using the setHeader
method on the response:
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.')
}
Reading cookies
You can read cookies inside an API Route using the cookies
request helper:
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const auth = req.cookies.authorization
// ...
}
Deleting cookies
You can delete cookies inside an API Route using the setHeader
method on the response:
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Set-Cookie', 'username=; Path=/; HttpOnly; Max-Age=0')
res.status(200).send('Cookie has been deleted.')
}
Was this helpful?