A 95% webview app, and why it shipped faster.
At CRED I led the app build, almost entirely as web inside a native shell. The decision framework, the bridge, config-driven flows, and what I'd change.
- Published
- 12 Jun 2024
- Length
- 5 min read
- Roles
- Product, Frontend, Architecture
- From the work on
- CRED
In 2022 at CRED I led the frontend for the app build. The decision that shaped everything else was made in the first week: about 95% of it would be web, built with Next.js and rendered inside a thin native shell. The remaining 5% would be native because it had to be.
This is not a universal answer. It was right for a product whose shape was still changing, where every screen would be rewritten more than once, and where an app store review on each change would have killed the iteration loop.
The decision framework
The trade is release velocity against native fidelity.
Native gives you gestures that feel exactly right, high refresh rate scrolling, system components, and direct access to the platform. It costs you a release process: store review, staged rollouts, and a long tail of users who never update. A bug in native code lives for weeks.
Web gives you a deploy that takes minutes and reaches every user at once. It costs you some fidelity, a cold start you have to manage, and a bridge to maintain.
The question I used for every feature was: does this need an OS capability, or does it need to change next week? The first is native. The second is web. When the answer was both, it was web with a native hook.
The 5% that had to be native:
- Auth. Session storage, device binding, biometrics. The web never sees a password.
- Payments. SDKs and payment intents are native by necessity.
- Push notifications. Registration, delivery and tap handling.
- Deep links. The native side resolves the link and tells the webview which route to open.
- The shell itself. Navigation container, status bar, safe areas, the back gesture.
Everything else, which is every screen a user actually looks at, was web.
The bridge
The bridge is the contract between the two halves, and it is the part worth getting right first. I designed it as a promise-based RPC over postMessage: typed methods, a request id on every call, a timeout on every promise, and a version number in every message.
type Methods = {
"auth.getToken": { params: Record<string, never>; result: { token: string; expiresAt: number } };
"payments.start": { params: { orderId: string }; result: { status: "success" | "failed" | "cancelled" } };
"nav.close": { params: { result?: unknown }; result: void };
"device.haptic": { params: { style: "light" | "medium" }; result: void };
};
type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: number };
const pending = new Map<string, Pending>();
export function call<M extends keyof Methods>(
method: M,
params: Methods[M]["params"],
timeoutMs = 8000,
): Promise<Methods[M]["result"]> {
const id = crypto.randomUUID();
return new Promise((resolve, reject) => {
const timer = window.setTimeout(() => {
pending.delete(id);
reject(new Error(`bridge timeout: ${method}`));
}, timeoutMs);
pending.set(id, { resolve: resolve as Pending["resolve"], reject, timer });
postToNative({ v: 2, id, method, params });
});
}Native replies on a single global callback. Anything without a matching id is ignored, which also makes replayed or late responses harmless.
type Reply = { id: string; result?: unknown; error?: { code: string; message: string } };
window.__onNativeMessage = (raw: string) => {
const msg = JSON.parse(raw) as Reply;
const p = pending.get(msg.id);
if (!p) return;
clearTimeout(p.timer);
pending.delete(msg.id);
if (msg.error) {
p.reject(Object.assign(new Error(msg.error.message), { code: msg.error.code }));
} else {
p.resolve(msg.result);
}
};
function postToNative(msg: object) {
const json = JSON.stringify(msg);
if (window.webkit?.messageHandlers?.bridge) {
window.webkit.messageHandlers.bridge.postMessage(json); // iOS, WKScriptMessageHandler
} else if (window.NativeBridge) {
window.NativeBridge.postMessage(json); // Android, @JavascriptInterface
} else {
throw new Error("no native bridge available");
}
}Three details carried most of the weight. Timeouts meant a native crash or a forgotten reply never left a spinner on screen forever. Request ids meant calls could overlap safely, which matters the moment two components mount at once and both want a token. Versioning meant the web could feature-detect: it reads the bridge version at boot, and a method the installed app lacks falls back to a web implementation, such as the web share dialog. Old app versions kept working against new web deploys, which is the whole point.
Config-driven flows
The second piece that paid for itself was describing screens as data. A flow is an ordered list of screens. A screen is a list of components from the UI library with props, bindings and actions. Actions can navigate, call an API, or call the bridge. The renderer is a lookup from type to component.
{
"id": "onboarding",
"version": 12,
"screens": [
{
"id": "welcome",
"components": [
{ "type": "Hero", "props": { "title": "Set up in two minutes", "art": "welcome" } },
{ "type": "Checklist", "props": { "items": ["Verify your number", "Pick a plan"] } },
{ "type": "Button", "props": { "label": "Start" }, "on": { "press": { "go": "verify" } } }
]
},
{
"id": "verify",
"skipIf": { "bridge": "auth.isVerified", "equals": true },
"components": [
{ "type": "OtpForm", "props": { "submitTo": "/v1/verify" }, "on": { "success": { "go": "plan" } } }
]
}
]
}The config is fetched at runtime and versioned, so a product change is a config publish. The core flows went through more than ten iterations, reordering screens, changing copy, adding and removing steps, without an app release for any of them. Hand-written screens remained for real interaction complexity, but the parts that changed most were exactly the parts that were data.
Perceived performance in a webview
A webview's enemy is the cold start: process spin-up, page load, script execution. Users do not care that the content is web. They care that a tab opens instantly.
- Preloaded shells. The native side keeps a warm webview with the app shell already loaded and hidden. Opening a web screen is a route change inside a running document, not a page load.
- Skeletons first. The shell paints a skeleton immediately and data fills it in. Nothing waits for a network response to paint.
- Prefetch on native intent. When native knows a screen is likely next, such as a tab being pressed, it tells the webview to prefetch the route and warm the API cache before the transition finishes.
- Cache headers. Hashed assets are
immutablewith a long max-age. HTML is revalidated with an ETag. The webview's HTTP cache does the rest. - One document. The webview never navigates to a new page. Client-side routing handles everything, and the native back button maps to
history.back()through the bridge, closing the webview only at the root.
A full chat flow, in web
Chat was the feature I was least sure about putting in a webview, and the one that most justified the decision. We built the full flow with the Sendbird JavaScript SDK: channel list, message list, typing indicators, read receipts, file attachments.
The native half was deliberately small. The bridge emitted foreground and background events, and the web connected or disconnected Sendbird accordingly so sockets did not linger. Chat push notifications were handled natively and deep-linked back into the web chat route with the channel id. File picking went through the native picker via the bridge, because file inputs inside webviews behave differently across Android manufacturers.
Chat UI changed constantly in the first months. Every one of those changes shipped without touching the app.
The internal UI library
Both the config-driven screens and the hand-written ones rendered from one component library. Tokens were shared with the native design system so a web screen and a native screen looked like the same app. The library had rules that a desktop-first library would not: no hover states, press feedback inside 100 ms, haptics through the bridge, layouts that respect env(safe-area-inset-*), and a loading state for every component because the network is always the slow part.
The same stack, elsewhere
The same webview architecture and component library carried another product I built at CRED, Predict and Win, a game inside the main app.
What I'd do differently
- Put versioning in the bridge from the first message. We added it later than we should have, and every day without it is unprotected coupling between app and web releases.
- Generate bridge types for TypeScript, Kotlin and Swift from one schema. Hand-maintaining three copies works until it does not.
- Validate flow configs at publish time against a JSON Schema, not at runtime in the renderer. A bad config should fail in the editor, not on a phone.
- Keep a per-screen escape hatch to go native. The right 5% is not fixed, and a screen that needs fidelity should be allowed to move.
What I'd carry forward
- Decide per feature: OS capability or weekly change? That one question sorts almost everything.
- A bridge is an API. Give it types, ids, timeouts and a version before giving it features.
- Describe the screens that change most as data, and render them from the library everyone else uses.
- Treat cold start as the product problem it is: warm shells, skeletons, prefetch on intent.
- Measure iteration speed, not just frame rate. Shipping without an app release was the feature.