McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Handle Paystack Webhooks in Nuxt
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 22, 2026

Handle Paystack Webhooks in Nuxt

To handle Paystack webhooks in Nuxt 3, create a server route at server/api/webhooks/paystack.post.ts. Read the raw request body, compute the HMAC SHA512 hash using your secret key from runtimeConfig, and compare it to the x-paystack-signature header. Process the event and return a 200 response immediately.

In this article

  1. 1. How Paystack Webhooks Work
  2. 2. The Webhook Server Route
  3. 3. Signature Verification Deep Dive
  4. 4. Process Events Idempotently
  5. 5. Testing Webhooks Locally
  6. 6. Deployment Considerations
  7. 7. Ship Payments Faster

How Paystack Webhooks Work

When a payment is completed (or fails, or a subscription changes), Paystack sends an HTTP POST request to a URL you configure in your dashboard. This POST request contains a JSON body with the event type and details.

The webhook arrives from Paystack's servers to your server. It does not go through the customer's browser. This is a server-to-server call, which is why it works perfectly with Nuxt server routes.

Common webhook events:

  • charge.success - A payment was completed
  • transfer.success - A transfer was completed
  • transfer.failed - A transfer failed
  • subscription.create - A new subscription was created
  • invoice.payment_failed - A recurring charge failed
  • refund.processed - A refund was processed

The Webhook Server Route

// server/api/webhooks/paystack.post.ts
import crypto from 'crypto';

export default defineEventHandler(async (event) => {
  var config = useRuntimeConfig();
  var secret = config.paystackSecretKey;

  // Read raw body for signature verification
  var rawBody = await readRawBody(event);

  if (!rawBody) {
    throw createError({ statusCode: 400, message: 'Empty body' });
  }

  // Verify signature
  var signature = getHeader(event, 'x-paystack-signature');
  var hash = crypto
    .createHmac('sha512', secret)
    .update(rawBody)
    .digest('hex');

  if (hash !== signature) {
    throw createError({ statusCode: 400, message: 'Invalid signature' });
  }

  // Parse the verified body
  var payload = JSON.parse(rawBody);
  var eventType = payload.event;
  var data = payload.data;

  // Process events
  if (eventType === 'charge.success') {
    var reference = data.reference;
    var amount = data.amount;
    var currency = data.currency;
    var customerEmail = data.customer.email;

    // Update order in database
    // await db.orders.updateOne(
    //   { reference: reference, status: { $ne: 'paid' } },
    //   { status: 'paid', amount: amount, paidAt: data.paid_at }
    // );

    console.log('Payment confirmed:', reference, amount, currency);
  }

  if (eventType === 'transfer.success') {
    // Handle successful transfer
    console.log('Transfer completed:', data.reference);
  }

  if (eventType === 'transfer.failed') {
    // Handle failed transfer, possibly retry or notify admin
    console.log('Transfer failed:', data.reference, data.reason);
  }

  // Return 200 immediately
  return { received: true };
});

Key points about this route:

  • The .post.ts suffix ensures only POST requests reach this handler.
  • readRawBody reads the body as a string before any JSON parsing, which is required for accurate HMAC verification.
  • The signature check runs before any event processing. If the signature does not match, the handler rejects the request immediately.

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Signature Verification Deep Dive

Paystack signs every webhook with HMAC SHA512 using your secret key. The signature is sent in the x-paystack-signature header. You must verify this signature to confirm the webhook actually came from Paystack.

Without signature verification, anyone who discovers your webhook URL could send fake events and trick your application into granting access or processing refunds.

The verification process:

  1. Read the raw request body as a string (not parsed JSON).
  2. Compute HMAC SHA512 of that exact string using your Paystack secret key.
  3. Compare the computed hash with the x-paystack-signature header value.
  4. If they match, the webhook is legitimate.

A common mistake is parsing the body as JSON first, then re-stringifying it. JSON.stringify(JSON.parse(body)) can reorder keys or change formatting, producing a different hash. Always use the raw, unparsed body.

Process Events Idempotently

Paystack may deliver the same webhook event more than once. Network timeouts, retries, and infrastructure issues can cause duplicates. Your handler must be idempotent: processing the same event twice should produce the same result as processing it once.

// Idempotent order fulfillment
if (eventType === 'charge.success') {
  var reference = data.reference;

  // Only update if not already paid
  // var result = await db.orders.updateOne(
  //   { reference: reference, status: 'pending' },
  //   { $set: { status: 'paid', paidAt: data.paid_at } }
  // );

  // if (result.modifiedCount === 0) {
  //   // Already processed, skip fulfillment
  //   return { received: true };
  // }

  // First time processing, send confirmation email, grant access, etc.
}

The status: 'pending' condition in the database query ensures the update only happens once. If the order is already marked as paid, the query matches zero documents and the fulfillment logic is skipped.

Testing Webhooks Locally

During development, Paystack cannot reach localhost. You need a tunnel:

# Using ngrok
ngrok http 3000

# Using Cloudflare Tunnel
cloudflared tunnel --url http://localhost:3000

Copy the HTTPS URL (like https://abc123.ngrok-free.app) and set it as your webhook URL in the Paystack test dashboard:

https://abc123.ngrok-free.app/api/webhooks/paystack

Make a test payment. Check your Nuxt server console for the logged output from your webhook handler. Once you confirm it works, update the URL for production.

Deployment Considerations

When deploying your Nuxt app, ensure the server routes work correctly:

  1. Vercel: Server routes become serverless functions automatically. Set PAYSTACK_SECRET_KEY in the Vercel environment variables.
  2. Netlify: Use the Nitro Netlify preset. Server routes become Netlify Functions.
  3. Node.js server: Deploy with node .output/server/index.mjs. Set environment variables on the host.
  4. Webhook URL: Update the webhook URL in the Paystack live dashboard to your production domain.
  5. Response time: Paystack expects a response within 30 seconds. If your event processing is slow, return 200 immediately and process asynchronously (use a queue or background job).

Set your production webhook URL to: https://yourdomain.com/api/webhooks/paystack

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Nuxt server routes can receive Paystack webhooks. Create a .post.ts file to restrict to POST requests only.
  • ✓Read the raw request body for signature verification. Do not parse it as JSON first.
  • ✓Compute the HMAC SHA512 hash of the raw body using your Paystack secret key and compare it to the x-paystack-signature header.
  • ✓Return 200 immediately after processing. Paystack retries if your endpoint returns anything other than 2xx within 30 seconds.
  • ✓Process webhooks idempotently. Paystack may send the same event more than once.
  • ✓In production, your Nuxt app needs a publicly accessible HTTPS URL for Paystack to reach your webhook endpoint.

Frequently Asked Questions

Can I handle Paystack webhooks in Nuxt without a separate backend?
Yes. Nuxt server routes run on the server and can receive HTTP POST requests from Paystack. You do not need Express, Django, or any separate backend. Everything lives in your Nuxt project.
How do I read the raw body in a Nuxt server route?
Use readRawBody(event) from the h3 library (included with Nuxt). This returns the body as a string before JSON parsing, which is required for HMAC signature verification.
What happens if my webhook endpoint returns a 500 error?
Paystack retries the webhook delivery. It makes multiple attempts with increasing intervals over several hours. Fix the error and the next retry will succeed. Your endpoint should always return 200 after processing to stop retries.
Can I test Paystack webhooks on localhost?
Not directly. Use ngrok or Cloudflare Tunnel to create a public HTTPS URL that tunnels to your local Nuxt dev server. Set that URL as the webhook URL in the Paystack test dashboard.
Should I process webhook events synchronously or asynchronously?
For simple operations like updating a database record, synchronous processing is fine. For slow operations like sending emails or generating PDFs, return 200 immediately and process the event in a background job or queue to avoid timeouts.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Verify Paystack Payments in Svelte and SvelteKit

Verify Paystack transactions in SvelteKit using server endpoints for popup verification and load functions for redirect callback verification. Covers amount validation, idempotent fulfillment, and SSR verification for instant results.

Read more

Handle Paystack Webhooks in Flask

Receive and verify Paystack webhooks in your Flask application. This guide covers accessing request.data for raw bytes, HMAC SHA-512 signature verification, processing charge.success events, and making handlers idempotent.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Paystack Balance and Settlement APIs Explained

Your Paystack dashboard shows you a balance number and a list of settlements. But when you need to reconcile programmatically, track pending payouts, or build financial reports, you need the API. This guide covers every endpoint, what each field means, and how to build reconciliation logic on top of them.

Read more

When Paystack Is Down: Building Graceful Degradation

Paystack will go down. Every payment provider does. The question is not whether it will happen but whether your app handles it gracefully or shows your customers a broken checkout page.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.