WhatsApp API in React and React Native Apps: Keep the Token on a Server

Using the WhatsApp API from React or React Native: why the token can’t go in the bundle, a backend route to call instead, and wa.me links to open chats.

Illustration: a React app and a phone app calling a server, which sends a WhatsApp order update (sample data)

A React or React Native app should never hold the WhatsApp Cloud API access token. The app calls your own backend, the backend calls Meta, and the token lives only in the backend’s environment. To let a user open a chat with you, a wa.me link is enough and needs no token at all.

This guide is about where the line sits in a React stack: why VITE_, NEXT_PUBLIC_ and EXPO_PUBLIC_ variables don’t hide anything, a Next.js route handler your web or mobile app can call, Expo Router API routes, opening WhatsApp from React and React Native, and a pre-release check for leaked tokens. It uses Meta’s official Cloud API on Graph API v27.0, the latest version in Meta’s changelog (4 November 2026). Building in Flutter instead? See the Flutter version.

Key takeaways

  • Any value your React or React Native code can read at run time is in the bundle, and anyone can read it there.
  • Vite, Next.js and Expo all say their public env prefixes end up in client code and must not hold secrets.
  • The app sends what happened (“order 1042 confirmed”); the server decides who gets which template.
  • Open chats with wa.me links: an <a> tag on the web, Linking.openURL in React Native.
  • Incoming messages go to a webhook on your server, never to the app.
  • Skip npm packages that drive WhatsApp Web: they aren’t Meta’s API.

Where the token leaks in Vite, Next.js and Expo

Every React toolchain has a way to pass settings into the build, and it’s easy to assume a setting in .env is secret. It isn’t, once client code reads it. Here is what each toolchain’s own docs say happens to a value:

ToolchainPrefix the client can readWhat the docs saySafe for the WhatsApp token?
Vite (React web)VITE_Exposed in client-side source code after bundling; should not contain API keys. Use a backend or serverless functions for secretsNo
Next.jsNEXT_PUBLIC_Inlined into the JavaScript sent to the browser at build timeNo
Next.jsNo prefixOnly available on the server, in route handlers and server codeYes, read in server code
Expo (React Native)EXPO_PUBLIC_Written into the app bundle and visible in plain text in the compiled app; never store secrets thereNo
Expo Router API routeNo prefix, in a +api.ts fileRuns on a server and isn’t included in the client bundle, unless client code imports itYes, once that server is deployed

Meta’s rule points the same way: its access tokens guide says never to hard-code app access tokens into client-side code or app binaries, and that calls using the app secret belong in server-side code only. Fetching the token from a config endpoint at start-up doesn’t help either; it’s then in memory on the user’s device and in its network traffic. Minifying or splitting it into pieces doesn’t help, because the app has to rebuild it to use it.

A leaked WhatsApp token lets someone send from your number until you revoke it, with template charges on your account and complaints counting against your number’s quality. So the app does what a user does (opens a chat, ticks “Send me updates on WhatsApp”, types a code) and your server does what the business does (sends templates and replies, receives webhooks, keeps the token and app secret).

A Next.js route handler that sends for the app

If your web app already runs on Next.js, a route handler is the natural backend: it runs on the server and reads the token from an environment variable with no public prefix. This one sends an order update. Note what it takes from the request (an order ID) and what it doesn’t (a phone number, a template or any text):

Lineapp/api/notify-order/route.ts
1import { send } from "../../../lib/whatsapp";
2import { base } from "../../../lib/whatsapp-types";
3import { getUser, findOrder } from "../../../lib/app";
4export async function POST(req: Request) {
5const user = await getUser(req);
6if (!user) return Response.json({ error: "Sign in first" }, { status: 401 });
7const { orderId } = (await req.json().catch(() => ({}))) as { orderId?: string };
8const order = orderId ? await findOrder(orderId) : null;
9if (!order || order.userId !== user.id) return Response.json({ error: "Order not found" }, { status: 404 });
10if (!order.whatsappOptIn) return Response.json({ error: "No WhatsApp opt-in" }, { status: 409 });
11await send({ ...base(order.phone), type: "template", template: { name: "order_update", language: { code: "en" }, components: [{ type: "body", parameters: [{ type: "text", text: order.firstName }, { type: "text", text: order.number }] }] } });
12return Response.json({ ok: true });
13}
  • lib/whatsapp.ts and lib/whatsapp-types.ts are the typed send() helper and payload types from our TypeScript guide, saved in the same lib/ folder. They read WHATSAPP_TOKEN and PHONE_NUMBER_ID, and only server code imports them.
  • getUser and findOrder are your own login and database code. The route checks that the order belongs to the signed-in user.
  • Opt-in (line 10). Meta only lets you message people who have opted in. Record that choice when the user ticks “Send me updates on WhatsApp”; see WhatsApp opt-in.
  • A template (line 11), because an order update starts the conversation. Templates are the only messages you can send outside a customer service window, and only APPROVED ones can be sent.
  • Add a rate limit per user in production, so a loop or a tampered client can’t run up your bill.

Not on Next.js? The same handler works in an Express app, a serverless function or any backend you already have; the Node.js guide shows the plain JavaScript version.

Expo Router API routes for a React Native backend

An Expo app built with Expo Router can keep its backend in the same project. A file ending in +api.ts defines an API route: a function that runs on a server when the route is matched. The handler has the same shape as the Next.js one above, export async function POST(request: Request), so the route code carries over almost line for line.

  1. Turn on server output. API routes need a server: set web.output to "server" in your app config, or use static output with the API routes option.
  2. Deploy the server to a secure host. The routes don’t run inside the phone app.
  3. Point native builds at it. For production builds, set the origin of the Expo Router config plugin to the deployed address, so the app knows where its API lives.
  4. Keep the WhatsApp code in server-only files. Expo’s docs warn that code a client file imports can still end up in the bundle, so never import lib/whatsapp.ts from a screen or component.

If you already run an API for your app, use that instead; the WhatsApp calls are just one more endpoint on it. What matters is that the token is read on a server and never by code that ships to phones.

Calling the route from a component or a screen

From the app, the call is an ordinary request to your own API. In a React web app on the same domain, the user’s session cookie goes along automatically:

LineReact (web)
1export async function notifyOrder(orderId: string) {
2const res = await fetch("/api/notify-order", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ orderId }) });
3if (!res.ok) throw new Error("Could not send the WhatsApp update");
4}

A React Native app has no page origin, so it uses the full URL of your API and the signed-in user’s own session token, from your login system, never Meta’s:

LineReact Native
1export async function notifyOrder(orderId: string, sessionToken: string) {
2const res = await fetch("https://api.example.com/api/notify-order", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + sessionToken }, body: JSON.stringify({ orderId }) });
3if (!res.ok) throw new Error("Could not send the WhatsApp update");
4}

If your mobile app calls the Next.js route, make getUser accept that Bearer session token as well as the cookie. The only secret in the app is the user’s own session, which can do no more than that user is allowed to do.

Sign-in codes, customer replies and delivery ticks follow the same pattern. For a WhatsApp OTP, the app sends the phone number and later the pasted code; the server creates the code, sends the authentication template and checks it (the flow is in WhatsApp OTP: authentication templates explained). Replies and “Delivered” or “Read” statuses reach a webhook, which must be a public HTTPS URL with a valid certificate, so a phone or browser tab can’t be one. Your server receives it, checks the signature with lib/signature.ts from the TypeScript guide, stores the event, and the app reads it from your API or gets it by push notification or WebSocket.

Opening WhatsApp: an anchor tag or Linking.openURL

Letting a user message you is the one WhatsApp job that belongs entirely in the app. WhatsApp’s click to chat link is https://wa.me/<number>, with the number in full international format and no plus sign, zeros, brackets or dashes, plus an optional ?text= with a URL-encoded message. No token, no Meta account.

WhereCode
React (web)<a href={"https://wa.me/919800000000?text=" + encodeURIComponent("Hi, I need help with order ORD-1042")} target="_blank" rel="noopener noreferrer">Chat on WhatsApp</a>
React Nativeimport { Linking } from "react-native";
React Nativeexport async function openWhatsApp(message: string) { try { await Linking.openURL("https://wa.me/919800000000?text=" + encodeURIComponent(message)); } catch { showFallback(); } }
  • Linking.openURL returns a promise that rejects when nothing can open the URL or the user cancels. showFallback() is yours to write: show the number as text, or offer a call.
  • Skip canOpenURL for this. On Android 11 and later it needs a <queries> entry in AndroidManifest.xml, and on iOS the scheme must be listed in LSApplicationQueriesSchemes. An https link opens anyway, in WhatsApp or in the browser.
  • Give the message context, such as the order number. The user can edit it, and nothing is sent until they tap send.

Once the user sends that message, the 24-hour customer service window opens and your server can reply with free-form messages. Link rules and QR codes are in how to create a WhatsApp link and QR code, and the free WhatsApp link generator builds one to test with.

Check your React codebase before you ship

A quick review catches most leaks before they reach users:

  1. Search the source for graph.facebook.com. It should appear only in server files: route handlers, +api.ts files or your API project.
  2. Search your env files for VITE_, NEXT_PUBLIC_ or EXPO_PUBLIC_ names that hold a WhatsApp token, app secret or Automate AI API key. Rename them without the prefix and read them only in server code.
  3. Search the build output, the files your build produces for the browser or the app bundle, for the first few characters of your token. If they’re there, the token has shipped.
  4. Check every server route that sends takes an ID, not a phone number, template name or message text, and checks the signed-in user.
  5. Check npm dependencies. Link and button components that build a wa.me link are harmless. Cloud API clients belong only in server code. Leave out WhatsApp Web automation such as whatsapp-web.js or Baileys, which logs in like a linked device: it isn’t Meta’s API, WhatsApp says unofficial apps break its Terms of Service and can get an account banned, and you get no approved templates or webhooks from Meta. More in official vs unofficial WhatsApp APIs.

React and React Native with Automate AI

If you’d rather not host Meta’s webhooks or build an inbox, Automate AI connects your number and handles them. Chats that start from your app’s wa.me button land in a shared inbox for your team, and approved templates go out as campaigns or from chatbots built without code.

For messages your app triggers, your backend can call Automate AI’s REST API, which has endpoints for contacts, messages, templates, campaigns and automations, and webhooks for events such as message received and status updates. The same rule applies: its API key goes in an Authorization: Bearer header from your server, never in the React or React Native bundle. A new key is shown once, when you create it. The API and webhooks are included on the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.

Frequently asked questions

Can I use the WhatsApp API directly in React Native?

You can make the request, but you shouldn’t: it needs an access token, and anything in a React Native bundle can be read. Call your own backend from the app and let the backend call Meta’s Cloud API.

How do I integrate the WhatsApp API in a React JS website?

Put the Cloud API calls in server code, such as a Next.js route handler or an Express endpoint, with the token in a server-only environment variable. The React components call that endpoint. For a “Chat with us” button, a wa.me link is enough.

Is it safe to put the token in a NEXT_PUBLIC_, VITE_ or EXPO_PUBLIC_ variable?

No. All three are built into the code that reaches the browser or phone, and Next.js, Vite and Expo all say not to store secrets in them.

How do I open WhatsApp from a React Native app?

Call Linking.openURL("https://wa.me/<number>?text=" + encodeURIComponent(message)) and catch the rejection, which happens when nothing can open the link.

Can a React Native app receive WhatsApp messages?

Not from Meta directly. Messages go to a webhook on your server, which stores them and passes them to the app by push notification, WebSocket or your own API.

Should I use whatsapp-web.js in a React Native app?

No. It automates WhatsApp Web, isn’t Meta’s Business API, and WhatsApp says unofficial apps can get accounts banned. Use the Cloud API from your server.

Sources

  1. Meta: Send messages
  2. Meta: Access tokens guide (client-side code and app secrets)
  3. Vite: Env variables and modes
  4. Next.js: Environment variables
  5. Expo: Environment variables
  6. Expo Router: API routes
  7. React Native: Linking
  8. WhatsApp Help Center: How to use click to chat

WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.