BakeNative is under active development. APIs may change.
Skip to Content
BakeNative

Native modules

Declare a native module once as a TypeScript spec, implement the generated Swift, Kotlin and Rust contracts, and call it from React and Octane apps, typed end to end.

BakeNative installs native modules into each Hermes runtime as JSI host functions under globalThis.native.<Module>.<member>. JS calls them directly, with no message bus. Values cross as a small value tree (null, boolean, number, string, array, object). Async members return a Promise.

import { native } from '@bake-native/react';

native.Haptics.impact('light');                      // sync
const { os, version } = native.Platform.info();      // sync, typed result
const ms = await native.Platform.delay(100);         // Promise

A module is declared once, as a TypeScript spec. Each language gets a contract in its own idiom, generated from it: a Swift protocol, a Kotlin abstract class, a Rust trait. You write a plain class that implements it; the generated code does the rest (conversion, threads, promises, errors, registration). Design: native module specs. Building a feature for more than one platform? Agree on the spec first and build every platform from it: Native features: spec first.

The registry is sealed before Hermes starts, so every module is installed before the bundle evaluates and is available to runtime handlers. A required bake runs without the app’s native registry. Read runtime values after the first commit. Each root's runtime only sees the modules of its own registry and of the app layer under it (there are no globals).

The spec

native/<name>/<Name>.native.ts, at the app's root (native/share/Share.native.ts):

import type { Int, NativeModule } from '@bake-native/core';

/** What `share` shows. */
export interface ShareData {
  title?: string;
  text?: string;
  url?: string;
}

export type ShareAction = 'shared' | 'dismissed';

export interface ShareResult {
  action: ShareAction;
}

/**
 * The system share sheet.
 * @throws E_UNAVAILABLE no window to present it from
 */
export interface Share extends NativeModule {
  /** Whether this host can share. */
  readonly available: boolean;
  /** Shows the share sheet; resolves when it closes. */
  share(data: ShareData): Promise<ShareResult>;
  /** How many shares this session. */
  count(): Int;
}
  • The one interface that extends NativeModule is the module (native.Share); the file is named after it.
  • Other exported interfaces are records; exported string unions are enums.
  • A method that returns Promise<T> is async; any other method is sync. readonly properties are constants, read once when the module is installed.
  • p?: T is an optional parameter; T | null may be null. Int is an integer (a JS number with an integer check).
  • onX(listener: (value: T) => void): Unsubscribe is an event. No other member takes a function.
  • ArrayBuffer and returning a module instance are not supported yet: the build says so, with the line.
SpecSwiftKotlinRust
string / number / Int / booleanString / Double / Int / BoolString / Double / Long / BooleanString / f64 / i64 / bool
T | null, p?: TT?T?Option<T>
T[] / Record<string, T>[T] / [String: T]List<T> / Map<String, T>Vec<T> / HashMap<String, T>
unknownBakeNativeAnyAny?Any
record / string unionstruct / enum: Stringdata class / enum classstruct / enum
Promise<T>async throws -> Tsuspend fun (): Tfn -> Result<T, ModuleError> (on a worker thread)

Implementing it

bake build generates the contract for each host (.bake/native/<target>/; on Apple the contracts are in the generated BakeNativeAppModules package, so add only BakeNativeBundleModules.swift to the app target, once). A module the app calls without a spec is a build error.

// iOS / macOS
final class ShareModule: ShareSpec {
  private weak var screen: UIViewController?
  init(screen: UIViewController) { self.screen = screen }       // its dependency
  var available: Bool { true }
  func count() -> Int { 0 }
  @MainActor func share(data: ShareData) async throws -> ShareResult { ... }   // runs on main
}
// Android
class ShareModule(private val activity: Activity) : ShareSpec() {
    override val available = true
    override fun count(): Long = 0
    override suspend fun share(data: ShareData): ShareResult = withContext(Dispatchers.Main) { ... }
}
// Windows
pub struct WinShare { window: HWND }
impl ShareSpec for WinShare {
    fn available(&self) -> bool { true }
    fn count(&self) -> Result<i64, ModuleError> { Ok(0) }
    fn share(&self, data: ShareData) -> Result<ShareResult, ModuleError> { ... }   // a worker thread
}

Threads

  • Sync members are called on the JS thread, inside the JS call. For UI work, queue it on main and return: DispatchQueue.main.async, runOnUiThread. Never wait for main from a sync member: main may be waiting for JS, and the app deadlocks. Make the member async instead.
  • Async members are called on a background thread, and the generated code settles the promise with the result or the error. For UI work: an @MainActor method in Swift (Swift runs it on main), withContext(Dispatchers.Main) in Kotlin, the host's UI post in Rust.

Errors

Throw BakeNativeModuleError(code: "E_PERMISSION", "...") (Swift), BakeNativeModuleError("E_PERMISSION", "...") (Kotlin) or return Err(ModuleError::new("E_PERMISSION", "...")) (Rust): JS gets an Error whose code it can branch on, labeled with the member (Share.share: ...). Any other error is E_NATIVE; a wrong argument is E_ARGUMENT before your code runs. List the codes in the spec with @throws.

Registering modules

Generated code registers every module the bundles call; nobody writes a registration table.

// Each screen: one registry, the modules the generated code creates itself plus the app's own,
// created with what they need.
BakeNativeView(bundle: bundle, modules: BakeNativeBundleModules.root(share: ShareModule(screen: self)))

BakeNativeBundleModules.root(...) has one parameter per app module the bundles call, typed by its spec: a module called unguarded is a required parameter, so a screen that leaves it out does not compile. A module the code guards with hasNative('Share') is optional (= nil): a screen without it runs without it. Android: bakeNativeView.modules.registerAll(BakeNativeBundleModules.root(share = ShareModule(this))) before load. Windows: bundle_modules::root(...) in the generated bakenative-app-modules crate.

register(_:) on the registry stays for modules the bundles do not name in code (dynamic access, tests).

Boot check

The compiler checks the host. What it cannot check is a bundle the host was not built with (an OTA update): before such a bundle runs, every module in its requires.nativeModules must be in the sealed registry, or the root fails closed, naming it:

native.OrderScreen: the bundle calls this module and this root does not register it (registered: Haptics, Platform, Storage); register it before launch

Dynamic access (native[name]) is checked by the JS proxy at call time. A hot updater can ask before it switches bundles: root.modules.missing(for: BakeNativeBundle(directory: download)).

On iOS and macOS, BakeNativeView registers the built-ins Platform, Storage (scoped by storageScope) and Haptics by default; pass builtinModules: false (or Options(builtinModules: false) on iOS) to opt out. Android's host registers Platform; Windows registers Platform (and Linking with its feature).

Built-inMembers
Platformos, info(): { os, version, hostProtocol }, delay(ms): Promise<number> (async example)
Storageget(key), set(key, value), remove(key), keys(). JSON values in UserDefaults; not for secrets.
Hapticssupported, impact(style?), notification(type?), selection() (a trackpad pattern on macOS)

Generated TypeScript

bake native types writes the declarations of native.<Name> from the specs into src/native.d.ts:

bake native types            # native/*/*.native.ts -> src/native.d.ts

--schema native-modules.json adds the modules of a schema a host wrote (BAKE_NATIVE_SCHEMA=<path> while a root installs its modules), for modules without a spec; several schemas give the union, and a member that differs between them is an error.

Adding a native function

The recipe is the same for people and for coding agents:

  1. Define: bake native new Clipboard writes native/clipboard/Clipboard.native.ts and, next to it, an implementation of the contract for each target in bake.config.ts (Clipboard.swift, Clipboard.kt, clipboard.rs, Clipboard.web.ts), with tests (--platform ios|macos|apple|android|windows|web keeps one; --target is the Kotlin package). A module from the registry comes with bake add clipboard instead. The tests call members through module.invoke("name", args) / invokeAsync, without a JS runtime, with the conversion and errors JS gets.
  2. Build: bake build generates the contracts and BakeNativeBundleModules, and compiles the implementations next to the spec into the registration. Pass the module to the screen (BakeNativeBundleModules.root(clipboard: ClipboardModule())); a module that lives in the host project (a brownfield screen's) keeps only its spec in native/<name>/.
  3. Check: bake native types, then bake check: a module the app calls without a spec, or without an implementation for a target it builds, fails. Commit the spec and src/native.d.ts.

Events

A member named on<Something> that takes a listener is an event: native → JS values, as many as the native side sends.

import type { Int, NativeModule, Unsubscribe } from '@bake-native/core';
export interface Battery extends NativeModule {
  onLevel(listener: (percent: Int) => void): Unsubscribe;
}
const stop = native.Battery.onLevel((percent) => setLevel(percent));
// later
stop();

The implementation gets an emitter and returns how to stop. It runs while at least one JS listener is subscribed, started once for the first and stopped after the last:

func onLevel(emit: @escaping @Sendable (Int) -> Void) throws -> BakeNativeSubscription {
  let observer = observeBatteryLevel { emit($0) }               // emit from any thread
  return BakeNativeSubscription { observer.invalidate() }
}
override fun onLevel(emit: (Long) -> Unit): BakeNativeSubscription {
    val receiver = registerBatteryReceiver { emit(it) }        // emit from any thread
    return BakeNativeSubscription { context.unregisterReceiver(receiver) }
}
fn on_level(&self, emit: Box<dyn Fn(i64) + Send + Sync>) -> Result<Subscription, ModuleError> {
    let watcher = start_watching(move |percent| emit(percent));
    Ok(Box::new(move || watcher.stop()))
}

On the web, <Module>.web.ts implements onLevel(emit) and returns its unsubscribe. Every host has events: iOS, macOS, Android, Windows and the web. Values emitted after the stop, or after the root closed, are dropped; closing a root cancels the sources it started. In tests, module.subscribe("onLevel") { value in … } starts an event without a JS runtime.

Props and host events

Root component props come from the host. They are installed before the bundle runs, so the first render sees them:

host.launch(bundle, props: ["user": "ada"])                   // macOS BakeNativeView
BakeNativeView(bundle: bundle, props: ["user": "ada"])           // iOS / SwiftUI
root.launch(bundle, props: ["user": "ada"])                   // any root
export function App(props) @{ <p>{'Hello ' + props.user}</p> }

Native → JS is a host event, sent from the view showing the page (main thread):

bakeNativeView.sendEvent("deeplink", json: #""myapp://pair?code=42""#)   // payload: JSON text
import { host } from '@bake-native/react';
const off = host.on('deeplink', (url) => navigate(url));   // returns unsubscribe

JS → native is a call on a module the screen registers (native.OrderScreen.setTip(2)). host.emit was removed: using it is a build error (host-emit) and a type error.

Batches that a host.on handler causes are applied like any other event. Events sent before hydration are delivered right after it. To type event payloads, augment HostEvents with declare module '@bake-native/core' { interface HostEvents { deeplink: string } }.

For a module with iOS and Android implementations, an unconditional call fails a macOS or Windows build at the call site. An event handler can use an explicit fallback:

function scan() {
  if (hasNative('Scanner')) return native.Scanner.scan();
  return enterCodeManually();
}

Every call to an optional module must be guarded. You can also select the implementation with import.meta.env.BAKE_TARGET. A module consisting only of an app-owned spec is supplied by the brownfield host through its generated root contract.

Snapshots, props and native calls

App-wide Strong mode automatically bakes and verifies the first screen for each native target and locale. The baker renders the root with its parameter defaults. Host props arrive after the first commit. Put native calls and capability checks in handlers or after the first render so the baked screen can match the device's first commit.

Web

On the web target there is no host. native.X.y() throws an error with code E_UNAVAILABLE unless you register a web implementation:

import { registerWebModule, hasNative } from '@bake-native/octane';
registerWebModule('Haptics', { impact() { navigator.vibrate?.(10); } });

On the web host.on receives nothing and host.props is {}.

A module's web implementation is its <Name>.web.ts, which the web build loads (the registry modules Clipboard, Linking, Share and Haptics have one). See System modules.

The web build checks each call of a module with a spec against it before the .web.ts code runs, as the hosts do: a wrong type, a missing record field, a value outside a string union, an element of the wrong type or too many arguments is E_ARGUMENT with the hosts' message (Share.share: argument 0: ShareContent: field "url" expected string, got number 5; an async member rejects). Fields a record does not declare are ignored, on every host. So a call that fails on iOS or Android fails on the web too.

C ABI (for other languages)

Include bakenative_native_modules.h from native/hermes/BakeNativeHermes/include to register native functions from a C host. The core's bake_set_engine_hook hands the host a borrowed engine on its JavaScript thread before the bundle runs. Register functions and constants with bake_engine_define_function, bake_engine_define_async_function and bake_engine_define_value. A callback receives the arguments as a bake_value array and returns an owned bake_value, or sets *error to throw. Settle asynchronous results with bake_engine_settle on that engine's JavaScript thread.

Cost

On an Apple Silicon Mac (release build, 100k calls), a no-op native call costs about 60–85 ns. A typed add(Int, Int) -> Int call costs about 330–430 ns including argument validation, and a plain JS function call costs about 5 ns.

On this page