Bird
Raised Fist0
NextJSframework~10 mins

Route handlers for webhooks in NextJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Route handlers for webhooks
Incoming HTTP Request
↓
Next.js Route Handler
↓
Parse Request Body
↓
Validate Webhook Signature
↓
Process Event
↓
Send 200 OK
↓
End
The webhook route handler receives a request, parses and validates it, then processes or rejects it accordingly.
Execution Sample
NextJS
export async function POST(req) {
  const body = await req.json();
  if (!isValidSignature(req)) {
    return new Response('Invalid signature', { status: 400 });
  }
  await handleEvent(body);
  return new Response('OK', { status: 200 });
}
This code handles a POST webhook request by validating the signature, processing the event, and responding.
Execution Table
StepActionInput/ConditionResultResponse Sent
1Receive POST requestRequest with JSON body and headersRequest object readyNo
2Parse JSON bodyRequest body JSONParsed body objectNo
3Validate signatureCheck signature headerSignature valid?No
4Signature valid?YesProceed to handle eventNo
5Handle eventParsed bodyEvent processedNo
6Send responseEvent processedResponse 200 OK sentYes
7If signature invalidNoSend 400 error responseYes
💡 Execution stops after sending either 200 OK or 400 error response.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
reqIncoming request objectSameSameSameSame
bodyundefinedParsed JSON objectParsed JSON objectParsed JSON objectParsed JSON object
signatureValidundefinedundefinedtrue or falsetrue or falsetrue or false
responseundefinedundefinedundefinedundefinedResponse object (200 or 400)
Key Moments - 3 Insights
Why do we check the signature before processing the event?
Checking the signature first (see step 3 and 4 in execution_table) ensures we only process requests from trusted sources, preventing fake or malicious webhook calls.
What happens if the signature is invalid?
If the signature is invalid (step 7), the handler immediately sends a 400 error response and stops processing, protecting the app from bad data.
Why do we parse the JSON body before validating the signature?
Parsing the JSON body (step 2) is needed to access the event data, but signature validation (step 3) usually uses headers and raw body; in Next.js, you may need to handle raw body carefully to validate signature correctly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response is sent if the signature is valid?
A400 Error
B200 OK
CNo response sent
D500 Server Error
💡 Hint
Check step 6 in the execution_table where response 200 OK is sent after valid signature.
At which step does the handler decide to reject the request due to invalid signature?
AStep 7
BStep 4
CStep 2
DStep 5
💡 Hint
Look at step 7 in the execution_table where 400 error is sent if signature is invalid.
If the JSON body parsing fails, what would happen in this flow?
AThe handler sends 400 error due to invalid signature
BThe handler sends 200 OK anyway
CThe handler never reaches signature validation
DThe handler processes event with empty body
💡 Hint
Parsing JSON happens at step 2; if it fails, the flow stops before signature validation at step 3.
Concept Snapshot
Next.js webhook route handlers receive POST requests.
Parse JSON body from request.
Validate webhook signature to ensure trust.
If valid, process event and respond 200 OK.
If invalid, respond 400 error and stop.
Always secure webhook endpoints to prevent fake calls.
Full Transcript
This visual execution trace shows how Next.js route handlers manage webhook POST requests. First, the handler receives the request and parses its JSON body. Then it validates the webhook signature to confirm the request is from a trusted source. If the signature is valid, the event is processed and a 200 OK response is sent. If the signature is invalid, the handler immediately sends a 400 error response and stops further processing. Variables like the request object, parsed body, signature validation status, and response evolve through these steps. Key beginner questions include why signature validation is done before processing, what happens on invalid signatures, and the importance of parsing the body correctly. The quiz tests understanding of response codes, decision points, and error handling in the flow.

Practice

(1/5)
1. What HTTP method should you use in a Next.js route handler to receive webhook events?
easy
A. GET
B. POST
C. PUT
D. DELETE

Solution

  1. Step 1: Understand webhook data sending

    Webhooks send data to your server, usually using the POST method to submit event payloads.
  2. Step 2: Match HTTP method in Next.js route handler

    To receive webhook data, your Next.js route handler must listen for POST requests.
  3. Final Answer:

    POST -> Option B
  4. Quick Check:

    Webhook data uses POST = POST [OK]
Hint: Webhooks send data with POST method, always listen for POST [OK]
Common Mistakes:
  • Using GET method which does not carry webhook payload
  • Using PUT or DELETE which are not standard for webhooks
  • Not specifying method and allowing all methods
2. Which of the following is the correct syntax to export a POST route handler in Next.js for a webhook?
easy
A. export function POST(req) { return new Response('ok') }
B. export default function handler(req, res) { res.send('ok') }
C. export async function get(req) { return Response.json('ok') }
D. export function postHandler(req, res) { res.json('ok') }

Solution

  1. Step 1: Identify Next.js route handler syntax

    Next.js route handlers export named functions matching HTTP methods, e.g., export function POST(req) { ... }
  2. Step 2: Check each option for correct syntax

    export function POST(req) { return new Response('ok') } uses correct named export POST with a Request object and returns a Response. Others use Express style or wrong method names.
  3. Final Answer:

    export function POST(req) { return new Response('ok') } -> Option A
  4. Quick Check:

    Named export POST with Request and Response = export function POST(req) { return new Response('ok') } [OK]
Hint: Use named export POST(req) returning Response for webhook handlers [OK]
Common Mistakes:
  • Using default export instead of named export for POST
  • Using lowercase 'post' instead of uppercase 'POST'
  • Mixing Express.js syntax with Next.js route handlers
3. Given this Next.js route handler code for a webhook, what will be the HTTP status code of the response?
export async function POST(req) {
  const data = await req.json();
  if (data.event === 'ping') {
    return new Response('pong', { status: 200 });
  }
  return new Response('ignored', { status: 204 });
}
medium
A. Always 204
B. Always 200
C. 200 if event is 'ping', otherwise 204
D. 500 on error

Solution

  1. Step 1: Analyze conditional response

    If the JSON body has event equal to 'ping', the handler returns status 200 with 'pong'. Otherwise, it returns status 204 with 'ignored'.
  2. Step 2: Understand status codes

    Status 200 means OK, 204 means No Content (successful but no response body expected). The code matches these conditions exactly.
  3. Final Answer:

    200 if event is 'ping', otherwise 204 -> Option C
  4. Quick Check:

    Conditional status 200 or 204 = 200 if event is 'ping', otherwise 204 [OK]
Hint: Check conditions returning different status codes in route handler [OK]
Common Mistakes:
  • Assuming always 200 regardless of condition
  • Confusing 204 with error status
  • Ignoring async/await for JSON parsing
4. Identify the error in this Next.js webhook route handler code:
export async function POST(req) {
  const body = await req.json;
  return new Response('Received');
}
medium
A. No error, code is correct
B. Response should be JSON, not plain text
C. POST function must be synchronous
D. Missing parentheses when calling req.json()

Solution

  1. Step 1: Check usage of req.json

    req.json is a function and must be called with parentheses: req.json()
  2. Step 2: Verify other parts

    Returning new Response with plain text is valid; async function is allowed. So only missing parentheses is error.
  3. Final Answer:

    Missing parentheses when calling req.json() -> Option D
  4. Quick Check:

    req.json() requires parentheses = Missing parentheses when calling req.json() [OK]
Hint: Always call req.json() as a function with parentheses [OK]
Common Mistakes:
  • Forgetting parentheses on req.json causing runtime error
  • Assuming POST must be synchronous
  • Thinking Response must be JSON always
5. You want to create a Next.js webhook route handler that only accepts POST requests, verifies a secret token in headers, and responds with status 401 if unauthorized. Which code snippet correctly implements this?
hard
A. export async function POST(req) { const token = req.headers.get('x-secret-token'); if (token !== 'mysecret') { return new Response('Unauthorized', { status: 401 }); } return new Response('Webhook received', { status: 200 }); }
B. export function GET(req) { const token = req.headers['x-secret-token']; if (token !== 'mysecret') { return new Response('Unauthorized', { status: 401 }); } return new Response('Webhook received', { status: 200 }); }
C. export async function POST(req, res) { if (req.headers['x-secret-token'] !== 'mysecret') { res.status(401).send('Unauthorized'); } else { res.status(200).send('Webhook received'); } }
D. export async function POST(req) { const token = req.headers.get('secret-token'); if (token === 'mysecret') { return new Response('Unauthorized', { status: 401 }); } return new Response('Webhook received', { status: 200 }); }

Solution

  1. Step 1: Check method and header access

    Webhook must use POST method and access headers with req.headers.get('header-name'). export async function POST(req) { const token = req.headers.get('x-secret-token'); if (token !== 'mysecret') { return new Response('Unauthorized', { status: 401 }); } return new Response('Webhook received', { status: 200 }); } uses POST and correct header name 'x-secret-token'.
  2. Step 2: Verify authorization logic and response

    If token mismatches, respond 401 Unauthorized; else respond 200 OK. export async function POST(req) { const token = req.headers.get('x-secret-token'); if (token !== 'mysecret') { return new Response('Unauthorized', { status: 401 }); } return new Response('Webhook received', { status: 200 }); } correctly implements this logic.
  3. Final Answer:

    Option A code snippet -> Option A
  4. Quick Check:

    POST + req.headers.get + 401 on bad token = export async function POST(req) { const token = req.headers.get('x-secret-token'); if (token !== 'mysecret') { return new Response('Unauthorized', { status: 401 }); } return new Response('Webhook received', { status: 200 }); } [OK]
Hint: Use POST, req.headers.get, and return 401 if token invalid [OK]
Common Mistakes:
  • Using GET instead of POST for webhook
  • Accessing headers as object instead of using .get()
  • Reversing authorization logic (401 on valid token)
  • Using Express style req, res in Next.js route handlers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard