Forms and Mutations
Learn how to handle form submissions and data mutations with Next.js.
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
Server-only form
With the Pages Router, you need to manually create API endpoints to handle securely mutating data on the server.
Then, call the API Route from the client with an event handler:
Form validation
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 to validate the form fields before mutating the data:
Error handling
You can use React state to show an error message when a form submission fails:
Displaying loading state
You can use React state to show a loading state when a form is submitting on the server:
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:
Setting cookies
You can set cookies inside an API Route using the setHeader
method on the response:
Reading cookies
You can read cookies inside an API Route using the cookies
request helper:
Deleting cookies
You can delete cookies inside an API Route using the setHeader
method on the response: