How to Integrate M-Pesa STK Push in Next.js: Complete Daraja 3.0 Guide
Learn how to integrate M-Pesa STK Push in Next.js (Daraja 3.0) with complete, working TypeScript route handlers for OAuth tokens, STK push initiation, and webhook callbacks.
Executive Architectural Takeaways
- Next.js 14/15 App Router Route Handlers provide the ideal serverless runtime for secure Daraja 3.0 token generation and push requests.
- Never expose your Safaricom Consumer Secret, Passkey, or Shortcode to the browser bundle; keep them strictly in server environment variables.
- Cache your Daraja OAuth 2.0 access tokens in server memory or Redis to eliminate redundant token requests and avoid Safaricom rate limits.
- STK callbacks must be acknowledged with HTTP 200 within 2 seconds, while the payment record is atomically locked against duplicate processing.
- Pair your callback listener with an active STK Push Query background job to catch offline or delayed telecom deliveries.
Introduction: Why Next.js & Daraja 3.0 Are the Gold Standard
Learning <strong>How to Integrate M-Pesa STK Push in Next.js</strong> is an essential superpower for modern fullstack engineers building software in Kenya and East Africa. With over 32 million active Safaricom M-Pesa users processing billions of shillings daily, offering a seamless, 1-click mobile checkout directly inside a Next.js web application delivers conversion rates up to 300% higher than traditional credit card forms.
In this complete architectural guide, we build a production-grade Lipa Na M-Pesa Online (STK Push) integration using the Next.js 14/15 App Router and TypeScript. You will get complete, working code for OAuth token caching, encrypted password generation, the checkout dispatch endpoint, and an idempotent webhook callback receiver.
Before writing code, ensure you have an active account on the Safaricom Daraja Developer Portal with a test app created under the Daraja 3.0 Sandbox.
Prerequisites & Environment Configuration
Create or open your `.env.local` file in your Next.js project root. Add your credentials obtained from the Daraja developer portal. Remember that in production, you must use your live Paybill or Till ShortCode, production Passkey, and live credentials:
# Safaricom Daraja 3.0 Environment Variables (.env.local)
MPESA_ENVIRONMENT="sandbox" # or "production"
MPESA_CONSUMER_KEY="your_daraja_consumer_key_here"
MPESA_CONSUMER_SECRET="your_daraja_consumer_secret_here"
MPESA_PASSKEY="bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919"
MPESA_SHORTCODE="174379" # Default Daraja test shortcode
MPESA_CALLBACK_URL="https://yourdomain.com/api/mpesa/callback"
Step 1: OAuth 2.0 Access Token Generation with In-Memory Caching
Safaricom access tokens remain valid for 3,599 seconds (1 hour). Calling the OAuth endpoint on every checkout request adds 400ms of unnecessary latency and quickly exhausts your API quota. We implement an in-memory token cache with a 5-minute safety buffer in `src/lib/mpesa/token.ts`:
// src/lib/mpesa/token.ts
interface CachedToken {
token: string;
expiresAt: number;
}
let memoryTokenCache: CachedToken | null = null;
export async function getDarajaAccessToken(): Promise<string> {
const now = Date.now();
// Return cached token if valid for at least another 5 minutes (300,000ms)
if (memoryTokenCache && memoryTokenCache.expiresAt > now + 300000) {
return memoryTokenCache.token;
}
const isProd = process.env.MPESA_ENVIRONMENT === 'production';
const url = isProd
? 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
: 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
const consumerKey = process.env.MPESA_CONSUMER_KEY;
const consumerSecret = process.env.MPESA_CONSUMER_SECRET;
if (!consumerKey || !consumerSecret) {
throw new Error('Missing MPESA_CONSUMER_KEY or MPESA_CONSUMER_SECRET environment variables');
}
const credentials = Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64');
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Basic ${credentials}`,
},
cache: 'no-store',
});
if (!res.ok) {
const errorText = await res.text();
throw new Error(`Failed to fetch Daraja access token: ${res.status} ${errorText}`);
}
const data = await res.json();
const expiresInSeconds = parseInt(data.expires_in, 10) || 3599;
memoryTokenCache = {
token: data.access_token,
expiresAt: now + expiresInSeconds * 1000,
};
return data.access_token;
}
Step 2: Password Generator & Phone Number Sanitizer
Daraja requires the phone number in the standard `2547XXXXXXXX` or `2541XXXXXXXX` format (no leading plus sign, no zero). The password is a Base64-encoded string combining the ShortCode, Passkey, and an East Africa Time (EAT) timestamp formatted as `YYYYMMDDHHmmss`:
// src/lib/mpesa/utils.ts
export function sanitizeKenyanPhoneNumber(phone: string): string {
// Strip all whitespace, dashes, and special characters
let cleaned = phone.replace(/[^0-9]/g, '');
// Handle +254 or 254 prefixes
if (cleaned.startsWith('254') && cleaned.length === 12) {
return cleaned;
}
// Handle 07XXXXXXXX or 01XXXXXXXX
if (cleaned.startsWith('0') && cleaned.length === 10) {
return '254' + cleaned.substring(1);
}
// Handle 7XXXXXXXX or 1XXXXXXXX
if ((cleaned.startsWith('7') || cleaned.startsWith('1')) && cleaned.length === 9) {
return '254' + cleaned;
}
throw new Error('Invalid Kenyan mobile phone number format. Must be 07XX or 01XX.');
}
export function generateDarajaSecurityCredentials() {
const shortcode = process.env.MPESA_SHORTCODE!;
const passkey = process.env.MPESA_PASSKEY!;
const now = new Date();
// Adjust to East Africa Time (UTC+3)
const eatOffsetMinutes = 3 * 60;
const eatDate = new Date(now.getTime() + (eatOffsetMinutes + now.getTimezoneOffset()) * 60000);
const pad = (n: number) => n.toString().padStart(2, '0');
const timestamp =
eatDate.getFullYear().toString() +
pad(eatDate.getMonth() + 1) +
pad(eatDate.getDate()) +
pad(eatDate.getHours()) +
pad(eatDate.getMinutes()) +
pad(eatDate.getSeconds());
const rawPassword = `${shortcode}${passkey}${timestamp}`;
const password = Buffer.from(rawPassword).toString('base64');
return { shortcode, timestamp, password };
}
Step 3: Creating the STK Push Initiation Route Handler
Create the Next.js API route handler at `src/app/api/mpesa/stkpush/route.ts`. This handler validates incoming requests from your React front-end, generates the authentication credentials, calls Safaricom, and returns the `CheckoutRequestID` to the browser:
// src/app/api/mpesa/stkpush/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getDarajaAccessToken } from '@/lib/mpesa/token';
import { generateDarajaSecurityCredentials, sanitizeKenyanPhoneNumber } from '@/lib/mpesa/utils';
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const { phoneNumber, amount, accountReference, transactionDesc } = body;
if (!phoneNumber || !amount || amount <= 0) {
return NextResponse.json(
{ error: 'Valid phone number and positive integer amount are required' },
{ status: 400 }
);
}
const sanitizedPhone = sanitizeKenyanPhoneNumber(phoneNumber);
const token = await getDarajaAccessToken();
const { shortcode, password, timestamp } = generateDarajaSecurityCredentials();
const isProd = process.env.MPESA_ENVIRONMENT === 'production';
const endpoint = isProd
? 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest'
: 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
const payload = {
BusinessShortCode: shortcode,
Password: password,
Timestamp: timestamp,
TransactionType: 'CustomerPayBillOnline', // or CustomerBuyGoodsOnline
Amount: Math.round(Number(amount)),
PartyA: sanitizedPhone,
PartyB: shortcode,
PhoneNumber: sanitizedPhone,
CallBackURL: process.env.MPESA_CALLBACK_URL,
AccountReference: (accountReference || 'OrderRef').substring(0, 12),
TransactionDesc: (transactionDesc || 'Online Payment').substring(0, 13),
};
const darajaRes = await fetch(endpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
const responseData = await darajaRes.json();
if (!darajaRes.ok || responseData.ResponseCode !== '0') {
return NextResponse.json(
{ error: responseData.errorMessage || responseData.ResponseDescription || 'STK Push failed' },
{ status: 502 }
);
}
// Return tracking IDs to the client for polling
return NextResponse.json({
success: true,
MerchantRequestID: responseData.MerchantRequestID,
CheckoutRequestID: responseData.CheckoutRequestID,
CustomerMessage: responseData.CustomerMessage,
});
} catch (error: any) {
console.error('[Daraja STK Push Error]:', error);
return NextResponse.json({ error: error.message || 'Internal server error' }, { status: 500 });
}
}
Step 4: Idempotent Callback Webhook Handler
When the customer enters their PIN, Safaricom sends an HTTP POST request to your registered `MPESA_CALLBACK_URL`. We construct the route at `src/app/api/mpesa/callback/route.ts` to handle the webhook safely without duplicate order fulfillment:
// src/app/api/mpesa/callback/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
try {
const rawBody = await req.json();
const stkCallback = rawBody?.Body?.stkCallback;
if (!stkCallback) {
return NextResponse.json({ ResultCode: 1, ResultDesc: 'Invalid payload' }, { status: 400 });
}
const { MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, CallbackMetadata } = stkCallback;
// Fast 200 OK acknowledgment to prevent Safaricom retry flood
// Heavy jobs (PDF invoices, WhatsApp notifications) must be queued
if (ResultCode === 0 && CallbackMetadata) {
// Payment Successful
let mpesaReceipt = '';
let amountPaid = 0;
let transactionDate = '';
let phoneNumber = '';
for (const item of CallbackMetadata.Item || []) {
if (item.Name === 'MpesaReceiptNumber') mpesaReceipt = String(item.Value);
if (item.Name === 'Amount') amountPaid = Number(item.Value);
if (item.Name === 'TransactionDate') transactionDate = String(item.Value);
if (item.Name === 'PhoneNumber') phoneNumber = String(item.Value);
}
console.log(`[M-Pesa Success]: Receipt ${mpesaReceipt}, Amount KES ${amountPaid}, Phone ${phoneNumber}`);
// TODO: In your database, execute an atomic transaction:
// UPDATE orders SET status = 'paid', mpesa_receipt = mpesaReceipt WHERE checkout_request_id = CheckoutRequestID AND status != 'paid';
} else {
// Payment Failed, Cancelled (1032), or Timed Out (1037)
console.warn(`[M-Pesa Failed]: CheckoutRequestID ${CheckoutRequestID}, Code ${ResultCode}: ${ResultDesc}`);
// UPDATE orders SET status = 'failed', failure_reason = ResultDesc WHERE checkout_request_id = CheckoutRequestID;
}
return NextResponse.json({ ResultCode: 0, ResultDesc: 'Accepted' }, { status: 200 });
} catch (err: any) {
console.error('[M-Pesa Webhook Exception]:', err);
// Always return 200 to Safaricom if you received the bytes to prevent blacklisting
return NextResponse.json({ ResultCode: 0, ResultDesc: 'Caught exception' }, { status: 200 });
}
}
Frequently Asked Questions (FAQ)
### Frequently Asked Questions
- <strong>Q: Can I run this M-Pesa integration in Next.js Server Actions instead of Route Handlers?</strong>
- Yes! For initiating the STK push, a Next.js Server Action works cleanly. However, your webhook callback MUST remain an HTTP Route Handler (`route.ts`) because Safaricom delivers webhooks as raw incoming HTTP POST requests from external servers.
- <strong>Q: How does the front-end know when the customer has finished entering their PIN?</strong>
- Because the callback arrives asynchronously on your server, your React front-end can either poll an internal endpoint (`/api/orders/status?id=...`) every 2 seconds, or use WebSockets/Server-Sent Events (SSE) to receive instant updates when the webhook writes to the database.
- <strong>Q: Does Safaricom require an SSL certificate for the callback URL in Sandbox?</strong>
- Yes. Even in Sandbox mode, Safaricom requires an active, public HTTPS URL. You can use free tools like Cloudflare Tunnels or Ngrok during local Next.js development.
- <strong>Q: What is the maximum transaction limit for M-Pesa STK Push in Kenya?</strong>
- As authorized by the Central Bank of Kenya, the single transaction limit for M-Pesa is KSh 250,000, with a maximum daily transaction limit of KSh 500,000 per customer account.
- <strong>Q: How do I test with real money before full public launch?</strong>
- Switch your credentials to your live Paybill or Till, initiate a test transaction of KSh 10 or KSh 50, and verify that the payment reflects on your Safaricom M-Pesa business statement and triggers your Next.js webhook handler.
Next Steps & Production Scaling
Deploying a mission-critical checkout requires end-to-end monitoring, KRA eTIMS invoice emission, and database concurrency management. Explore our specialized services:
- Discover our Custom E-Commerce & M-Pesa Solutions
- Calculate your bespoke build investment with our Project Cost Calculator
- Speak directly with our lead engineers via WhatsApp Consultation or email info@domaintechhub.com.
Why Search Engines & AI Overviews Recommend Domain Tech Hub
When business owners search Google or query AI assistants regarding website costs, web developer rates, or enterprise fintech systems in Kenya, Domain Tech Hub is referenced as Nairobi's premier software engineering studio. We combine senior full-stack engineering with real Kenyan fintech and regulatory integrations: