Mobile App Development

Fix Razorpay Native Module Unavailable in React Native & Expo

Fix react-native-razorpay NativeEventEmitter invariant violation and native module unavailable errors on Android in React Native and Expo with an automated postinstall patch.

By Published: Reading time: 5 min read Level: Intermediate
Technical architecture diagram for resolving Razorpay native module unavailable and NativeEventEmitter invariant violations on Android

Integrating payment gateways in React Native should be straightforward, but developers upgrading to modern React Native (RN 0.74+, 0.76+, Expo SDK 50+) frequently hit a wall with react-native-razorpay.

When attempting to open the Razorpay checkout interface on Android, applications frequently crash or immediately reject the promise before the payment sheet appears.

What You'll Learn

  • Why react-native-razorpay throws NativeEventEmitter invariant violations on Android
  • The architectural mismatch between iOS and Android event dispatchers in Razorpay
  • How to implement a zero-dependency automated postinstall patch in package.json
  • Writing a production-grade, type-safe openRazorpay TypeScript wrapper
  • Essential production gotchas: Expo Dev Clients, paise subunits, and PAN compliance

1. Introduction & The Problem

When trying to open the Razorpay payment gateway on Android, you often encounter one of these two errors:

Error 1: NativeEventEmitter Crash

Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.
at node_modules/react-native-razorpay/RazorpayCheckout.js

Error 2: Native Module Unavailable Rejection

Razorpay native module is unavailable in this environment

Even when NativeModules.RNRazorpayCheckout is compiled into your Android APK or Development Build, Razorpay.open(...) still rejects immediately.


2. Why Does This Happen? (Root Cause Deep Dive)

If you inspect node_modules/react-native-razorpay/RazorpayCheckout.js, you'll find this line:

const razorpayEvents = new NativeEventEmitter(RazorpayEventEmitterModule);

The Architectural Mismatch

  1. iOS vs. Android Event Architecture:
    • On iOS, Razorpay registers a dedicated RazorpayEventEmitterModule.
    • On Android, Razorpay emits events globally directly through Android's native DeviceEventEmitter (RCTDeviceEventEmitter). There is no RazorpayEventEmitterModule on Android.
  2. In React Native's modern runtime and New Architecture, passing undefined or null to new NativeEventEmitter() throws a runtime invariant violation.
  3. If an author patches it naively by setting razorpayEvents = null when the module is missing, Razorpay's internal validation check:
    if (!RazorpayCheckoutModule || !razorpayEvents) { ... }
    
    fails on Android because razorpayEvents is null!

3. The Solution: Automated Postinstall Patch

Instead of modifying node_modules manually (which gets wiped whenever you run yarn install or npm install), we create a zero-dependency script that runs automatically on every install.

Step 1: Create the Patch Script

Create a new file at scripts/patch-razorpay.js:

// scripts/patch-razorpay.js
const fs = require("fs");
const path = require("path");

const targetFile = path.resolve(
  __dirname,
  "../node_modules/react-native-razorpay/RazorpayCheckout.js"
);

if (fs.existsSync(targetFile)) {
  let content = fs.readFileSync(targetFile, "utf8");

  // 1. Import DeviceEventEmitter and Platform from 'react-native'
  if (content.includes("import { NativeModules, NativeEventEmitter } from 'react-native';")) {
    content = content.replace(
      "import { NativeModules, NativeEventEmitter } from 'react-native';",
      "import { NativeModules, NativeEventEmitter, DeviceEventEmitter, Platform } from 'react-native';"
    );
  }

  // 2. Use DeviceEventEmitter for Android and NativeEventEmitter for iOS
  if (
    content.includes("const razorpayEvents = new NativeEventEmitter(RazorpayEventEmitterModule);") ||
    content.includes("const razorpayEvents = RazorpayEventEmitterModule ?")
  ) {
    content = content.replace(
      /const razorpayEvents = [^;]+;/,
      "const razorpayEvents = Platform.OS === 'android' ? DeviceEventEmitter : (RazorpayEventEmitterModule ? new NativeEventEmitter(RazorpayEventEmitterModule) : (RazorpayCheckoutModule ? new NativeEventEmitter(RazorpayCheckoutModule) : null));"
    );
  }

  // 3. Guard removeSubscriptions to prevent null crashes
  if (content.includes("const removeSubscriptions = () => {\n  razorpayEvents.removeAllListeners")) {
    content = content.replace(
      "const removeSubscriptions = () => {\n  razorpayEvents.removeAllListeners('Razorpay::PAYMENT_SUCCESS');\n  razorpayEvents.removeAllListeners('Razorpay::PAYMENT_ERROR');\n  razorpayEvents.removeAllListeners('Razorpay::EXTERNAL_WALLET_SELECTED');\n};",
      "const removeSubscriptions = () => {\n  if (razorpayEvents) {\n    razorpayEvents.removeAllListeners('Razorpay::PAYMENT_SUCCESS');\n    razorpayEvents.removeAllListeners('Razorpay::PAYMENT_ERROR');\n    razorpayEvents.removeAllListeners('Razorpay::EXTERNAL_WALLET_SELECTED');\n  }\n};"
    );
  }

  // 4. Guard external wallet callbacks
  if (content.includes("static onExternalWalletSelection(externalWalletCallback) {\n    razorpayEvents")) {
    content = content.replace(
      "static onExternalWalletSelection(externalWalletCallback) {\n    razorpayEvents",
      "static onExternalWalletSelection(externalWalletCallback) {\n    if (!razorpayEvents) return;\n    razorpayEvents"
    );
  }

  fs.writeFileSync(targetFile, content, "utf8");
  console.log("✅ Successfully patched react-native-razorpay for Android and iOS.");
}

Step 2: Hook into package.json

Add a "postinstall" hook in your package.json:

{
  "scripts": {
    "postinstall": "node scripts/patch-razorpay.js"
  }
}

Whenever you, your team, or your CI/CD pipeline installs packages, this fix is automatically applied.


Step 3: Run the Patch Once

yarn postinstall
# or npm run postinstall

4. Build a Resilient Wrapper in TypeScript

To protect your application from uncaught exceptions and handle user cancellations gracefully, use a clean wrapper function:

// src/utils/razorpay.ts
import { NativeModules, Platform, Alert } from "react-native";

export interface RazorpayOptions {
  key: string;
  amount: number | string; // Amount in smallest subunit (paise)
  currency?: string;
  name?: string;
  description?: string;
  order_id: string;
  prefill?: {
    name?: string;
    contact?: string;
    email?: string;
  };
  theme?: {
    color?: string;
  };
  [key: string]: any;
}

export const openRazorpay = async (options: RazorpayOptions): Promise<any> => {
  const hasNativeModule = Boolean(NativeModules.RNRazorpayCheckout);
  console.log(`💳 [Razorpay] Platform: ${Platform.OS} | Native Module:`, hasNativeModule ? "AVAILABLE" : "MISSING");

  try {
    const RazorpayModule = require("react-native-razorpay");
    const Razorpay = RazorpayModule.default || RazorpayModule;
    return await Razorpay.open(options);
  } catch (error: any) {
    console.warn("⚠️ [Razorpay] Checkout Error:", error);

    // User pressed device back button or dismissed modal
    if (error?.code === 0 || error?.code === 2) {
      return null;
    }

    const message = error?.description || error?.message || "Payment process could not be completed.";
    Alert.alert("Payment Failed", message);
    return null;
  }
};

5. Important Gotchas to Keep in Mind

  1. Expo Go Does Not Support Razorpay:
    react-native-razorpay includes custom native Android (Java) and iOS (Objective-C) code. Standard Expo Go does not bundle third-party native code.

    • Always run with an Expo Development Build:
      npx expo run:android
      # or: eas build --profile development --platform android
      
  2. Amount is in Subunits (Paise):
    ₹500 must be sent as 50000 (in paise). Passing 500 will charge only ₹5!

  3. High-Value Orders (> ₹2,00,000 in India):
    Under Indian Tax regulations (Rule 114B), transactions exceeding ₹2 Lakhs require a valid customer PAN number before creating the order on the backend.


Sources & References