0
0
NextJSframework~5 mins

Route handlers for webhooks in NextJS

Choose your learning style9 modes available
Introduction

Route handlers let your Next.js app listen and respond to webhook events from other services. This helps your app react automatically when something happens elsewhere.

You want to receive payment notifications from a payment gateway.
You need to update your database when a user changes info on a third-party app.
You want to trigger actions when a GitHub repository gets a new issue or pull request.
You want to log events from external services in your app.
You want to automate workflows based on external events without user input.
Syntax
NextJS
export async function POST(request) {
  const body = await request.json();
  // handle webhook data here
  return new Response('Webhook received', { status: 200 });
}

Use HTTP methods like POST to receive webhook data.

Parse the request body to access webhook payload.

Examples
Basic POST handler that logs webhook data and responds with OK.
NextJS
export async function POST(request) {
  const data = await request.json();
  console.log('Webhook data:', data);
  return new Response('OK', { status: 200 });
}
Handles specific event types from webhook payload.
NextJS
export async function POST(request) {
  const event = await request.json();
  if (event.type === 'payment_success') {
    // process payment
  }
  return new Response('Processed', { status: 200 });
}
Optional GET handler to check if webhook route is active.
NextJS
export async function GET() {
  return new Response('Webhook endpoint active', { status: 200 });
}
Sample Program

This route handler receives webhook POST requests, logs the event, and responds based on event type. It also handles errors gracefully.

NextJS
export async function POST(request) {
  try {
    const webhookEvent = await request.json();
    console.log('Received webhook event:', webhookEvent);
    // Example: respond differently based on event type
    if (webhookEvent.type === 'user_signup') {
      // handle user signup event
      return new Response('User signup processed', { status: 200 });
    }
    return new Response('Event received', { status: 200 });
  } catch (error) {
    console.error('Error processing webhook:', error);
    return new Response('Bad Request', { status: 400 });
  }
}
OutputSuccess
Important Notes

Always respond quickly to webhook requests to avoid timeouts.

Validate webhook signatures if the service supports it for security.

Use environment variables to store secret keys for webhook verification.

Summary

Route handlers in Next.js let you receive and process webhook events.

Use POST method to handle incoming webhook data.

Always respond with a status to confirm receipt to the webhook sender.