Bird
Raised Fist0
NextJSframework~10 mins

HTTP method handlers (GET, POST) in NextJS - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - HTTP method handlers (GET, POST)
Request arrives
Check HTTP method
Run GET handler
Send GET response
Request ends
When a request comes in, Next.js checks its HTTP method. It runs the matching handler (GET or POST) and sends back the response.
Execution Sample
NextJS
export async function GET(request) {
  return new Response('Hello GET');
}

export async function POST(request) {
  return new Response('Hello POST');
}
This code defines two handlers: one for GET requests and one for POST requests, each sending a simple text response.
Execution Table
StepIncoming Request MethodHandler ChosenActionResponse Sent
1GETGET handlerRun GET function'Hello GET'
2POSTPOST handlerRun POST function'Hello POST'
3PUTNo handlerNo matching function405 Method Not Allowed
4DELETENo handlerNo matching function405 Method Not Allowed
💡 Execution stops after sending response or if no handler matches the HTTP method.
Variable Tracker
VariableStartAfter GET RequestAfter POST RequestAfter PUT Request
request.methodundefinedGETPOSTPUT
handler chosennoneGET handlerPOST handlernone
responsenone'Hello GET''Hello POST'405 Method Not Allowed
Key Moments - 3 Insights
Why does a PUT request get no response from these handlers?
Because the code only defines GET and POST handlers. PUT requests have no matching function, so Next.js returns a 405 Method Not Allowed response as shown in execution_table row 3.
Can both GET and POST handlers run for the same request?
No. Only the handler matching the request's HTTP method runs. For example, a GET request runs only the GET handler (execution_table row 1).
What happens if the POST handler takes time to respond?
The POST handler is async, so Next.js waits for it to finish before sending the response. This is shown by the async function in the execution_sample.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table. What response is sent when the request method is POST?
A'Hello POST'
B'Hello GET'
C405 Method Not Allowed
DNo response
💡 Hint
Check execution_table row 2 under 'Response Sent'
At which step does the handler chosen become 'none' due to no matching function?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table rows 3 and 4 for 'Handler Chosen'
If you add a PUT handler, how would the response for a PUT request change in the variable_tracker?
Ahandler chosen would stay 'none'
Brequest.method would change from 'PUT' to 'POST'
Cresponse would change from '405 Method Not Allowed' to the PUT handler's response
Dresponse would stay 'Hello GET'
💡 Hint
See variable_tracker row 'response' for PUT request and imagine adding a PUT handler
Concept Snapshot
Next.js API routes use exported async functions named after HTTP methods.
Define GET(request) for GET requests and POST(request) for POST requests.
Next.js calls the matching handler based on request.method.
If no handler matches, Next.js returns 405 Method Not Allowed by default.
Handlers return Response objects to send back data.
This pattern keeps server code clear and organized.
Full Transcript
In Next.js, when a request arrives, the framework looks at the HTTP method like GET or POST. It then runs the matching exported async function named GET or POST. For example, if the request method is GET, Next.js runs the GET handler function and sends its response. If the method is POST, it runs the POST handler. If there is no handler for the method, Next.js returns a 405 Method Not Allowed response. This way, you can organize your server code by HTTP method. Each handler receives the request object and returns a Response. This example shows simple handlers returning text responses for GET and POST. The execution table traces how requests with different methods choose handlers and what responses are sent. The variable tracker shows how request.method, handler chosen, and response change step by step. Key moments clarify why some methods get no response and how async handlers work. The quiz tests understanding of which handler runs and what response is sent. This pattern helps keep server logic clear and easy to maintain.

Practice

(1/5)
1. In Next.js API routes, how do you define a handler for a GET request?
easy
A. Define a function named handleGetRequest and call it manually.
B. Export an async function named GET from the route file.
C. Use app.get() inside the route file.
D. Export a function named getHandler from the route file.

Solution

  1. Step 1: Understand Next.js route handler naming

    Next.js expects exported async functions named after HTTP methods like GET or POST to handle those requests.
  2. Step 2: Identify the correct naming convention

    Only exporting an async function named GET will handle GET requests automatically.
  3. Final Answer:

    Export an async function named GET from the route file. -> Option B
  4. Quick Check:

    GET handler = async function named GET [OK]
Hint: Name the function exactly GET to handle GET requests [OK]
Common Mistakes:
  • Using incorrect function names like getHandler
  • Trying to call handlers manually
  • Using Express.js style app.get() in Next.js route files
2. Which of the following is the correct syntax to define a POST handler in a Next.js route file?
easy
A. export async function POST(request) { /* code */ }
B. export async function post(request) { /* code */ }
C. export function POST(request) { /* code */ }
D. export async function handlePOST(request) { /* code */ }

Solution

  1. Step 1: Check function naming and case sensitivity

    Next.js requires the handler function to be named exactly POST in uppercase to handle POST requests.
  2. Step 2: Confirm async keyword usage

    Handler functions should be async to handle asynchronous operations like reading request body.
  3. Final Answer:

    export async function POST(request) { /* code */ } -> Option A
  4. Quick Check:

    POST handler = async function named POST [OK]
Hint: Use uppercase POST and async keyword for POST handlers [OK]
Common Mistakes:
  • Using lowercase 'post' instead of uppercase 'POST'
  • Omitting async keyword
  • Wrong function names like handlePOST
3. Given this Next.js route handler code, what will be the response to a POST request?
export async function POST(request) {
  const data = await request.json();
  return new Response(JSON.stringify({ message: `Hello, ${data.name}!` }), { status: 200 });
}

And the client sends JSON {"name": "Alice"} in the POST body.
medium
A. SyntaxError due to missing await
B. Empty response with status 200
C. {"message":"Hello, Alice!"}
D. Error: request.json() is not a function

Solution

  1. Step 1: Understand request.json() usage

    The code uses await request.json() to parse the JSON body sent by the client, which contains {"name": "Alice"}.
  2. Step 2: Construct response with personalized message

    The response JSON string includes the message "Hello, Alice!" using the parsed data.name.
  3. Final Answer:

    {"message":"Hello, Alice!"} -> Option C
  4. Quick Check:

    POST JSON parsed and response includes name [OK]
Hint: Use await request.json() to read POST JSON body [OK]
Common Mistakes:
  • Forgetting to await request.json()
  • Returning empty or wrong response
  • Misnaming the data property
4. Identify the error in this Next.js route file code for handling GET and POST requests:
export async function GET() {
  return new Response('Hello GET');
}

export function POST(request) {
  const data = request.json();
  return new Response(`Hello ${data.name}`);
}
medium
A. POST handler should be named post in lowercase
B. GET handler should not return Response directly
C. GET handler must accept a request parameter
D. POST handler is missing async keyword and await for request.json()

Solution

  1. Step 1: Check POST handler async usage

    The POST handler calls request.json() which returns a promise, so it must be awaited and the function must be async.
  2. Step 2: Confirm GET handler and naming

    The GET handler is correctly async and returns a Response; naming and parameters are correct.
  3. Final Answer:

    POST handler is missing async keyword and await for request.json() -> Option D
  4. Quick Check:

    Async + await needed for request.json() in POST [OK]
Hint: Always use async and await when calling request.json() [OK]
Common Mistakes:
  • Not marking POST handler async
  • Not awaiting request.json()
  • Incorrect handler function names
5. You want to create a Next.js route that responds to both GET and POST requests. The GET returns a JSON list of items, and the POST adds a new item sent in JSON body. Which is the best way to structure your route file?
hard
A. Export async functions named GET and POST; GET returns JSON list; POST reads JSON body and returns updated list.
B. Export a single function handling both GET and POST by checking request.method manually.
C. Use middleware to separate GET and POST logic in different files.
D. Define GET and POST as methods inside a class and export the class.

Solution

  1. Step 1: Understand Next.js route handler pattern

    Next.js expects separate exported async functions named after HTTP methods like GET and POST to handle those requests cleanly.
  2. Step 2: Structure handlers for each method

    Define GET to return the JSON list and POST to read the JSON body and return the updated list, each in their own async function.
  3. Final Answer:

    Export async functions named GET and POST; GET returns JSON list; POST reads JSON body and returns updated list. -> Option A
  4. Quick Check:

    Separate GET and POST async functions = clean Next.js pattern [OK]
Hint: Use separate async GET and POST functions for clarity [OK]
Common Mistakes:
  • Combining GET and POST in one function
  • Using classes or middleware unnecessarily
  • Not returning proper JSON responses