HTTP method handlers let your Next.js app respond differently to GET or POST requests. This helps your app know what to do when someone visits a page or sends data.
0
0
HTTP method handlers (GET, POST) in NextJS
Introduction
When you want to show data on a page (GET request).
When you want to save or update data sent from a form (POST request).
When building an API route that handles different actions based on request type.
When you want to separate reading data from sending data in your app.
Syntax
NextJS
export async function GET(request) { // handle GET request return new Response('Hello from GET'); } export async function POST(request) { // handle POST request const data = await request.json(); return new Response(`Received: ${JSON.stringify(data)}`); }
Each HTTP method (GET, POST) is a separate exported async function.
The request object contains details about the incoming request.
Examples
This handles only GET requests and returns a simple text response.
NextJS
export async function GET(request) { return new Response('This is a GET response'); }
This handles POST requests, reads JSON data sent by the client, and responds with it.
NextJS
export async function POST(request) { const data = await request.json(); return new Response(`You sent: ${JSON.stringify(data)}`); }
This example shows both GET and POST handlers in the same file, responding differently.
NextJS
export async function GET(request) { return new Response('GET method called'); } export async function POST(request) { return new Response('POST method called'); }
Sample Program
This Next.js API route responds with a greeting for GET requests. For POST requests, it reads JSON data sent by the client and replies with that data in the response.
NextJS
export async function GET(request) { return new Response('Hello! You made a GET request.'); } export async function POST(request) { const data = await request.json(); return new Response(`Hello! You sent: ${JSON.stringify(data)}`); }
OutputSuccess
Important Notes
Always return a Response object from your handlers.
Use await request.json() to read JSON data from POST requests.
GET requests usually fetch data; POST requests usually send data.
Summary
HTTP method handlers let your Next.js app respond differently to GET and POST requests.
Define separate async functions named GET and POST in your route file.
Use the request object to read data sent by the client, especially in POST.