What you will learn
- Create a route handler that responds to GET and POST requests
- Return JSON responses with appropriate status codes
- Handle a form submission on the server and validate its data
The back end is the code that runs on a server rather than in the browser. It handles tasks the browser should not, such as checking data, talking to a database or using secret API keys. In the Next.js App Router, you can create an API endpoint with a route.ts file, for example app/api/contact/route.ts, which becomes available at /api/contact.
A route handler exports functions named after HTTP methods. GET is for reading data and POST is for sending new data. Inside POST, await request.json() reads a JSON body, and Response.json() sends a reply. Use status codes to describe the result: 200 or 201 for success, 400 when the request data is invalid, and 500 when something fails on the server.
For forms inside your own Next.js app, Server Actions are another option: an async function marked with "use server" that a form can call directly. Whichever approach you use, the rules are the same. Validate every field on the server, never trust data from the browser, keep secrets in environment variables, and return a clear success or error message to the user.


