> For AI agents: the complete documentation index is available at /next/llms.txt, the full documentation bundle is available at /next/llms-full.txt.

# Native Modules

When developing Lynx applications, you may encounter scenarios where you need to interact with native platform APIs not covered by Lynx. Or, you might want to reuse existing native platform code in your Lynx application. Regardless of the reason, you can use [**Native Modules**](/next/guide/spec.md#nativemodules) to seamlessly connect your JavaScript code with native code, allowing you to call native platform functions and APIs from your JavaScript code. The following will detail how to write a native module.

The basic steps for writing a native module are as follows:

1. Use TypeScript to **declare your typed interface specification**.
2. Use your interface specification to **write your Lynx application code**.
3. Follow your interface specification to **write your native platform code** and connect your native code to the Lynx runtime environment.

Next, this guide will demonstrate these steps through an example of building a native module.

:::info
Currently, native modules can only be used in [Background Thread Scripting](/next/guide/spec.md#background-thread-scripting).
:::

## Local Persistent Storage Module

This guide aims to show you how to write a local persistent storage module that enables your Lynx application to use JavaScript code to store data persistently locally.

To implement local persistent storage on different platforms, use the matching platform native API or the Lynx C/C++ APIs:

- Android: [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)
- iOS: [NSUserDefaults](https://developer.apple.com/documentation/foundation/nsuserdefaults)
- HarmonyOS: [Preferences](https://developer.huawei.com/consumer/en/doc/harmonyos-references/_preferences)
- Desktop (Node-API): Lynx C/C++ APIs and the Weak Node-API C++ wrapper


### Declare a Typed Interface Specification
The interface specification of a native module serves as a bridge between the native code and the Lynx JavaScript runtime, defining the methods and data types passed between them.
The steps to declare an interface specification are as follows:
1. **Create a Lynx project**: Refer to the [Create a Lynx Project](/next/guide/start/quick-start.md#create-a-new-lynx-project) guide to create your Lynx project.
2. **Create a new type declaration file**: Create a new file named `src/typing.d.ts` in your Lynx project.
3. **Implement the interface specification**: Implement the interface specification of the native module in the `typing.d.ts` file.
:::info
You can view the types available in the specification and their corresponding native types in the [Type Mapping Table](#type-mapping-table).
:::
The following is the implementation of the interface specification for the local persistent storage module:
```typescript title="typing.d.ts"
declare let NativeModules: {
  NativeLocalStorageModule: {
    setStorageItem(key: string, value: string): void;
    getStorageItem(key: string, callback: (value: string) => void): void;
    clearStorage(): void;
  };
};
```
`NativeModules` is a global built-in object provided by Lynx in the JavaScript runtime. It serves as the access point for all native modules, and all native module declarations must be defined within it.
### Write Your Lynx Application Code
Next, write your application code in `src/App.tsx` within your Lynx project.
The following is the `App.tsx` for the local persistent storage module. It includes an area to display the content read from local storage and three buttons for reading, writing, and clearing local storage.

**This is an example below: local-storage**

**Bundle:** `dist/main.lynx.bundle`

```tsx {11,19,24}
// Copyright 2025 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.

import { useEffect, useState } from "@lynx-js/react";

export function App() {
  const [storedValue, setStoredValue] = useState<string | null>(null);

  const setStorage = () => {
    NativeModules.NativeLocalStorageModule.setStorageItem(
      "testKey",
      "Hello, ReactLynx!",
    );
    getStorage();
  };

  const getStorage = () => {
    NativeModules.NativeLocalStorageModule.getStorageItem("testKey", (value) => {
      setStoredValue(value);
    });
  };

  const clearStorage = () => {
    NativeModules.NativeLocalStorageModule.clearStorage();
    setStoredValue(null);
  };

  useEffect(() => {
    getStorage();
  }, []);

  const containerStyle = {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    height: "100vh",
  } as const;

  const contentBoxStyle = {
    border: "1px solid #ccc",
    padding: "2px",
    marginBottom: "20px",
    borderRadius: "5px",
    width: "300px",
    textAlign: "center",
  } as const;

  const buttonContainerStyle = {
    display: "flex",
    flexDirection: "column",
    width: "max-content",
  } as const;

  const buttonStyle = {
    padding: "2px",
    margin: "5px",
    backgroundColor: "#ec644c",
    borderRadius: "5px",
    fontSize: "16px",
    boxShadow: "0 2px 4px rgba(0, 0, 0, 0.2)",
    flexShrink: "0",
  };

  const textStyle = {
    fontSize: "18px",
    margin: "10px 0",
    color: "#333",
  };

  const buttonTextStyle = {
    fontSize: "18px",
    margin: "10px 0",
    color: "#fffffe",
    alignSelf: "center",
  };

  return (
    <view style={containerStyle}>
      <view style={contentBoxStyle}>
        <text style={textStyle}>
          Current stored value: {storedValue || "None"}
        </text>
      </view>
      <view style={buttonContainerStyle}>
        <view style={buttonStyle} bindtap={setStorage}>
          <text style={buttonTextStyle}>Set storage: Hello, ReactLynx!</text>
        </view>
        <view style={buttonStyle} bindtap={getStorage}>
          <text style={buttonTextStyle}>Read storage</text>
        </view>
        <view style={buttonStyle} bindtap={clearStorage}>
          <text style={buttonTextStyle}>Clear storage</text>
        </view>
      </view>
    </view>
  );
}

```


### Write Your Native Platform Code
Now, you can start writing the native platform code.

iOSAndroidHarmonyOSDesktop (Node-API)

#### Prepare Your Xcode Project

First, follow the [Build Lynx Explorer for iOS](https://github.com/lynx-family/lynx/tree/develop/explorer/darwin/ios) guide to create a Lynx Explorer project locally and open it with Xcode.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/doc/native-modules-ios-step1.png)

Next, right-click on the `modules` folder in the Lynx Explorer project and select `New File...` to create the header and source files for the native module.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/doc/native-modules-ios-step2.png)

Then, use the `Cocoa Touch Class` template.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/doc/native-modules-ios-step3.png)

Name the class `NativeLocalStorageModule`. You can choose to create it in either `Objective-C` or `Swift`. Then click `Next` to complete the file creation.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/doc/native-modules-ios-step4.png)

#### Implement Your Native Module

:::info
You need to implement an additional static method `name` in the native module to return the exported name of your native module. Also, implement an additional static method `methodLookup` in the native module to map the names of the methods to be exported to their corresponding selectors.
:::


**Objective-C**

```objective-c {6} title="explorer/darwin/ios/lynx_explorer/LynxExplorer/modules/NativeLocalStorageModule.h"

#import <Foundation/Foundation.h>
#import <Lynx/LynxModule.h>

NS_ASSUME_NONNULL_BEGIN

@interface NativeLocalStorageModule : NSObject <LynxModule>

@end

NS_ASSUME_NONNULL_END

```
```objective-c {18-20,22-27} title="explorer/darwin/ios/lynx_explorer/LynxExplorer/modules/NativeLocalStorageModule.m"
#import "NativeLocalStorageModule.h"

@interface NativeLocalStorageModule()
@property (strong, nonatomic) NSUserDefaults *localStorage;
@end

@implementation NativeLocalStorageModule

static NSString *const NativeLocalStorageKey = @"MyLocalStorage";

- (instancetype)init {
    if (self = [super init]) {
        _localStorage = [[NSUserDefaults alloc] initWithSuiteName:NativeLocalStorageKey];
    }
    return self;
}

+ (NSString *)name {
    return @"NativeLocalStorageModule";
}

+ (NSDictionary<NSString *, NSString *> *)methodLookup {
    return @{
        @"setStorageItem": NSStringFromSelector(@selector(setStorageItem:value:)),
        @"getStorageItem": NSStringFromSelector(@selector(getStorageItem:callback:)),
        @"clearStorage": NSStringFromSelector(@selector(clearStorage))
    };
}

- (void)setStorageItem:(NSString *)key value:(NSString *)value {
    [self.localStorage setObject:value forKey:key];
}

- (void)getStorageItem:(NSString *)key callback:(void(^)(NSString *value)) callback{
    NSString *value = [self.localStorage stringForKey:key];
    callback(value);
}

- (void)clearStorage {
    NSDictionary *keys = [self.localStorage dictionaryRepresentation];
    for (NSString *key in keys) {
        [self.localStorage removeObjectForKey:key];
    }
}

@end

```


**Swift**

:::tip
Lynx Explorer is a project built with Objective-C. If you wish to implement a native module with Swift, please refer to [Importing Objective-C into Swift](https://developer.apple.com/documentation/swift/importing-objective-c-into-swift) to import the required Lynx header file `LynxModule.h`.
:::
```objective-c title="explorer/darwin/ios/lynx_explorer/LynxExplorer/modules/LynxExplorer-Bridging-Header.h"

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import <Lynx/LynxModule.h>


```
```swift {6-8,10-16} title="explorer/darwin/ios/lynx_explorer/LynxExplorer/modules/NativeLocalStorageModule.swift"

import Foundation

@objcMembers
public final class NativeLocalStorageModule: NSObject, LynxModule {

    public static var name: String {
        return "NativeLocalStorageModule"
    }

    public static var methodLookup: [String : String] {
        return [
            "setStorageItem": NSStringFromSelector(#selector(setStorageItem(_:value:))),
            "getStorageItem": NSStringFromSelector(#selector(getStorageItem(_:completion:))),
            "clearStorage": NSStringFromSelector(#selector(clearStorage))
        ]
    }

    private let localStorage: UserDefaults
    private static let storageKey = "MyLocalStorage"

    public init(param: Any) {
      guard let suite = UserDefaults(suiteName: NativeLocalStorageModule.storageKey) else {
          fatalError("Failed to initialize UserDefaults with suiteName: \(NativeLocalStorageModule.storageKey)")
      }
      localStorage = suite
      super.init()
    }

    public override init() {
        guard let suite = UserDefaults(suiteName: NativeLocalStorageModule.storageKey) else {
            fatalError("Failed to initialize UserDefaults with suiteName: \(NativeLocalStorageModule.storageKey)")
        }
        localStorage = suite
        super.init()
    }

    func setStorageItem(_ key: String, value: String) {
        localStorage.set(value, forKey: key)
    }

    objc func getStorageItem(_ key: String, completion:(NSString) -> Void) {
      if let value = localStorage.string(forKey: key) {
          completion(value as NSString)
      } else {
          completion("" as NSString)
      }
    }

    func clearStorage() {
        localStorage.dictionaryRepresentation().keys.forEach {
            localStorage.removeObject(forKey: $0)
        }
    }

}

```


Next, you need to register your native module into the Lynx runtime environment.

Add the following registration code to the `setupLynxEnv` method in the `explorer/darwin/ios/lynx_explorer/LynxExplorer/LynxInitProcessor.m` file of the Lynx Explorer project to register your native module with the global configuration of the Lynx runtime environment.


**Objective-C**

```objective-c {7} title="explorer/darwin/ios/lynx_explorer/LynxExplorer/LynxInitProcessor.m"

#import "NativeLocalStorageModule.h"

- (void)setupLynxEnv {
  // ...

  // register global JS module
  [globalConfig registerModule:NativeLocalStorageModule.class];

  // ...
}


NS_ASSUME_NONNULL_END

```


**Swift**

:::tip
Lynx Explorer is a project built with Objective-C. If you want to use Swift native modules in Objective-C files, please refer to [Importing Swift into Objective-C](https://developer.apple.com/documentation/swift/importing-swift-into-objective-c) to generate and import the `LynxExplorer-Swift.h` header file.
:::
```objective-c {7} title="explorer/darwin/ios/lynx_explorer/LynxExplorer/LynxInitProcessor.m"

#import "LynxExplorer-Swift.h"

- (void)setupLynxEnv {
  // ...

  // register global JS module
  [globalConfig registerModule:NativeLocalStorageModule.class];

  // ...
  }

NS_ASSUME_NONNULL_END

```


#### Run Your Code

Once you've prepared everything, you can now build and run your code.

First, follow the [Build and Run iOS Lynx Explorer](https://github.com/lynx-family/lynx/tree/develop/explorer/darwin/ios#build-ios-app) guide to build Lynx Explorer and install it on your phone.

Next, refer to the [Install Dependencies & Start the Development Server](/next/guide/start/quick-start.md#start-developing) guide to install dependencies and start the development server in the root directory of your Lynx project.

Install dependencies:


```sh [npm]
npm install
```

```sh [yarn]
yarn install
```

```sh [pnpm]
pnpm install
```

```sh [bun]
bun install
```

```sh [deno]
deno install
```

Start the development server:


```sh [npm]
npm run dev
```

```sh [yarn]
yarn run dev
```

```sh [pnpm]
pnpm run dev
```

```sh [bun]
bun run dev
```

```sh [deno]
deno run npm:dev
```

You'll see a QR code and an artifact link in the console. Use Lynx Explorer to scan the QR code or enter the artifact link to open your Lynx page.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/doc/native-modules-demo-ios-en.gif)

First, follow the [Build Lynx Explorer for Android](https://github.com/lynx-family/lynx/tree/develop/explorer/android) guide to create a Lynx Explorer project locally.

Next, create a new `NativeLocalStorageModule.java` or `NativeLocalStorageModule.kt` file in the `explorer/android/lynx_explorer/src/main/java/com/lynx/explorer/modules/` path of the Lynx Explorer project. Then, inherit from `LynxModule` to implement the `NativeLocalStorageModule` native module.

:::info
You need to add the `@LynxMethod` annotation to the methods that need to be exported in the native module.
:::


**Java**

```java {22,30,37} title="explorer/android/lynx_explorer/src/main/java/com/lynx/explorer/modules/NativeLocalStorageModule.java"
package com.lynx.explorer.modules;

import android.content.Context;
import android.content.SharedPreferences;

import com.lynx.jsbridge.LynxMethod;
import com.lynx.jsbridge.LynxModule;
import com.lynx.tasm.behavior.LynxContext;
import com.lynx.react.bridge.Callback;

public class NativeLocalStorageModule extends LynxModule {
  private static final String PREF_NAME = "MyLocalStorage";
  public NativeLocalStorageModule(Context context) {
    super(context);
  }

  Context getContext() {
    LynxContext lynxContext = (LynxContext) mContext;
    return lynxContext.getContext();
  }

  @LynxMethod
  public void setStorageItem(String key, String value) {
    SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.apply();
  }

  @LynxMethod
  public void getStorageItem(String key, Callback callback) {
    SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    String value = sharedPreferences.getString(key, null);
    callback.invoke(value);
  }

  @LynxMethod
  public void clearStorage() {
    SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.apply();
  }
}

```


**Kotlin**

```kotlin {18,26,32} title="explorer/android/lynx_explorer/src/main/java/com/lynx/explorer/modules/NativeLocalStorageModule.kt"

package com.lynx.explorer.modules

import android.content.Context
import com.lynx.jsbridge.LynxMethod
import com.lynx.jsbridge.LynxModule
import com.lynx.tasm.behavior.LynxContext
import com.lynx.react.bridge.Callback

class NativeLocalStorageModule(context: Context) : LynxModule(context) {
  private val PREF_NAME = "MyLocalStorage"

  private fun getContext(): Context {
    val lynxContext = mContext as LynxContext
    return lynxContext.getContext()
  }

  @LynxMethod
  fun setStorageItem(key: String, value: String) {
    val sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    val editor = sharedPreferences.edit()
    editor.putString(key, value)
    editor.apply()
  }

  @LynxMethod
  fun getStorageItem(key: String, callback: Callback) {
    val sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    callback(sharedPreferences.getString(key, null))
  }

  @LynxMethod
  fun clearStorage() {
    val sharedPreferences = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    val editor = sharedPreferences.edit()
    editor.clear()
    editor.apply()
  }
}

```


Next, you need to register your native module with the Lynx runtime environment.

Add the following registration code to the `Init` method in the `explorer/android/lynx_explorer/src/main/java/com/lynx/explorer/modules/LynxModuleAdapter.java` file of the Lynx Explorer project to register your native module with the Lynx runtime environment. Here, you need to specify the name of the native module you are exporting, which must be consistent with your interface specification.

```java {4} title="explorer/android/lynx_explorer/src/main/java/com/lynx/explorer/modules/LynxModuleAdapter.java"

  public void Init(Context context) {
    // ......

    LynxEnv.inst().registerModule("NativeLocalStorageModule", NativeLocalStorageModule.class);

    // ......
  }

```

After preparing everything, you can now build and run your code.

First, follow the [Compile and Run Android Lynx Explorer](https://github.com/lynx-family/lynx/tree/develop/explorer/android#build-and-run) guide to build Lynx Explorer from source code and install it on your phone.

Then, refer to the [Install Dependencies & Start the Development Server](/next/guide/start/quick-start.md#start-developing) guide to install dependencies and start the development server in the root directory of your Lynx project.

Install dependencies:


```sh [npm]
npm install
```

```sh [yarn]
yarn install
```

```sh [pnpm]
pnpm install
```

```sh [bun]
bun install
```

```sh [deno]
deno install
```

Start the development server:


```sh [npm]
npm run dev
```

```sh [yarn]
yarn run dev
```

```sh [pnpm]
pnpm run dev
```

```sh [bun]
bun run dev
```

```sh [deno]
deno run npm:dev
```

You will see a QR code in the console. Use Lynx Explorer to scan the QR code to open the page.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/doc/native-modules-demo-android-en.gif)

First, follow the [Build Lynx Explorer for HarmonyOS](https://github.com/lynx-family/lynx/tree/develop/explorer/harmony) guide to create a Lynx Explorer project locally.

Next, create a new `NativeLocalStorageModule.ets` file in the Lynx Explorer project and inherit from `LynxModule` in the `@lynx/lynx` package to implement the `NativeLocalStorageModule` native module.

:::info
You can add the `@Sendable` annotation to the Module class to convert it into a Sendable Module. Only the methods of a Sendable Module are synchronous; all other methods are asynchronous. The return value of an asynchronous method is `null`.
:::

```typescript title="NativeLocalStorageModule.ets"
import { LynxContext, LynxModule } from '@lynx/lynx';
import common from '@ohos.app.ability.common';
import { preferences } from '@kit.ArkData';

export class NativeLocalStorageModule extends LynxModule {
  private static readonly PREF_NAME: string = "NativeLocalStorageModule";
  private dataPreferences: preferences.Preferences | null = null;

  constructor(context: LynxContext, param?: Object) {
    super(context, param);
    this.initPreferencesSync();
  }

  private initPreferencesSync() {
    try {
      this.dataPreferences = preferences.getPreferencesSync(
        getContext(), 
        { name: NativeLocalStorageModule.PREF_NAME }
      );
      console.info("Preferences initialization succeeded.");
    } catch (error) {
      console.error(`Failed to initialize preferences: ${error}`);
    }
  }

  public setStorageItem(key: string, value: string) {
    if (!this.dataPreferences) {
      console.error("Preferences instance is not initialized.");
      return;
    }

    try {
      this.dataPreferences.putSync(key, value);
      this.dataPreferences.flushSync();
      console.info(`Storage item set successfully. key=${key}`);
    } catch (err) {
      console.error(`Failed to set storage item. key=${key}, error=${err.message}`);
    }
  }

  public getStorageItem(key: string, callback: (value: string)=> void) {
    if (!this.dataPreferences) {
      console.error("Preferences instance is not initialized.");
      callback("");
      return;
    }

    try {
      const value = this.dataPreferences.getSync(key, "");
      callback(value as string);
      return;
    } catch (err) {
      console.error(`Failed to get storage item. key=${key}, error=${err.message}`);
      callback("");
      return;
    }
  }

  public clearStorage() {
    if (!this.dataPreferences) {
      console.error("Preferences instance is not initialized.");
      return;
    }

    try {
      this.dataPreferences.clearSync();
      this.dataPreferences.flushSync();
      console.info("Storage cleared successfully.");
    } catch (err) {
      console.error(`Failed to clear storage. error=${err.message}`);
    }
  }
}

```

Next, register the native module with the Lynx runtime environment.

In the aboutToAppear method of the explorer/harmony/lynx_explorer/src/main/ets/pages/Lynx.ets file in your Lynx Explorer project, add the following registration code to register the native module with the Lynx runtime environment. Here, you need to specify the name of the native module, which must be consistent with the name in the interface specification above.

:::info
Register a regular Module in `this.modules` , and a Sendable Module in `this.sendableModules` .
:::

```typescript {8-10,12} title="src/main/ets/pages/Lynx.ets"
import { NativeLocalStorageModule } from '../module/NativeLocalStorageModule';

@Entry
@Component
struct Lynx {
  aboutToAppear() {
    // `param` is an optional constructor parameter for the module
    this.modules.set('NativeLocalStorageModule', {
      moduleClass: NativeLocalStorageModule
    });
    // Register Sendable Modules to this.sendableModules
  }
}
```

Once you've prepared everything, you can now build and run your code.

First, follow the [Build and Run Harmony Lynx Explorer](https://github.com/lynx-family/lynx/tree/develop/explorer/harmony) guide to build Lynx Explorer and install it on your phone.

Next, refer to the [Install Dependencies & Start the Development Server](/next/guide/start/quick-start.md#start-developing) guide to install dependencies and start the development server in the root directory of your Lynx project.

Install dependencies:


```sh [npm]
npm install
```

```sh [yarn]
yarn install
```

```sh [pnpm]
pnpm install
```

```sh [bun]
bun install
```

```sh [deno]
deno install
```

Start the development server:


```sh [npm]
npm run dev
```

```sh [yarn]
yarn run dev
```

```sh [pnpm]
pnpm run dev
```

```sh [bun]
bun run dev
```

```sh [deno]
deno run npm:dev
```

You'll see a QR code and an artifact link in the console. Use Lynx Explorer to scan the QR code or enter the artifact link to open your Lynx page.

![demo](https://lf-lynx.tiktok-cdns.com/obj/lynx-artifacts-oss-sg/lynx-website/assets/native-modules-demo-harmony.gif)

On Desktop (Node-API), use the Lynx C/C++ APIs to register native capabilities
with the Lynx runtime. Native Module methods are exposed to `NativeModules`
through the Weak Node-API environment owned by the Lynx JavaScript runtime, and
the registration entry point is `LYNX_REGISTER_NATIVE_MODULE`.

The [`@lynx-js/weak-node-api`](https://www.npmjs.com/package/@lynx-js/weak-node-api)
npm package publishes the Weak Node-API headers, including `napi.h`,
`node_api.h`, `weak_napi_defines.h`, and `weak_napi_undefs.h`. Add it to your
native library project and include its `headers/` directory in the build so
your code can use the `Napi::` C++ wrapper types.

The example below matches the TypeScript declaration above and exports
`NativeLocalStorageModule`.

```cpp title="shared/nativeModule/NativeLocalStorageModule.cc"
#include <lynx/registration.h>

#include "napi.h"

#ifdef USE_WEAK_SUFFIX_NAPI
#include "weak_napi_defines.h"
#endif

#include <string>
#include <unordered_map>

namespace {

std::unordered_map<std::string, std::string> g_storage;

void Check(napi_env env, napi_status status) {
  if (status != napi_ok) {
    napi_throw_error(env, nullptr, "N-API call failed");
  }
}

void SetFunction(
    napi_env env,
    napi_value object,
    const char* name,
    napi_callback callback) {
  napi_value function;
  Check(env, napi_create_function(
      env, name, NAPI_AUTO_LENGTH, callback, nullptr, &function));
  Check(env, napi_set_named_property(env, object, name, function));
}

Napi::Value SetStorageItem(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  // Method:
  //   setStorageItem(
  //     key: string,
  //     value: string,
  //   ): void
  // types/napi-native-module.d.ts
  if (info.Length() < 2) {
    return env.Undefined();
  }
  Napi::String key = info[0].As<Napi::String>();
  Napi::String value = info[1].As<Napi::String>();
  g_storage[key.Utf8Value()] = value.Utf8Value();
  return env.Undefined();
}

Napi::Value GetStorageItem(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  // Method:
  //   getStorageItem(
  //     key: string,
  //     callback: function,
  //   ): void
  // types/napi-native-module.d.ts
  if (info.Length() < 2) {
    return env.Undefined();
  }
  Napi::String key = info[0].As<Napi::String>();
  Napi::Function callback = info[1].As<Napi::Function>();
  auto iter = g_storage.find(key.Utf8Value());
  std::string value = iter == g_storage.end() ? "" : iter->second;
  callback.Call({Napi::String::New(env, value)});
  return env.Undefined();
}

Napi::Value ClearStorage(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  // Method:
  //   clearStorage(): void
  // types/napi-native-module.d.ts
  g_storage.clear();
  return env.Undefined();
}

napi_value SetStorageItemCallback(napi_env env, napi_callback_info info) {
  return SetStorageItem(Napi::CallbackInfo(env, info));
}

napi_value GetStorageItemCallback(napi_env env, napi_callback_info info) {
  return GetStorageItem(Napi::CallbackInfo(env, info));
}

napi_value ClearStorageCallback(napi_env env, napi_callback_info info) {
  return ClearStorage(Napi::CallbackInfo(env, info));
}

void BindNativeLocalStorageModule(napi_env env, napi_value exports) {
  SetFunction(env, exports, "setStorageItem", SetStorageItemCallback);
  SetFunction(env, exports, "getStorageItem", GetStorageItemCallback);
  SetFunction(env, exports, "clearStorage", ClearStorageCallback);
}

static napi_value CreateNativeLocalStorageModule(
    ::lynx::registration::LynxNapiEnv env,
    ::lynx::registration::LynxNapiValue exports,
    const char* module_name,
    void* opaque) {
  (void)module_name;
  (void)opaque;
  BindNativeLocalStorageModule(env, exports);
  return exports;
}

}  // namespace

LYNX_REGISTER_NATIVE_MODULE(
    "NativeLocalStorageModule",
    CreateNativeLocalStorageModule,
    nullptr)

#ifdef USE_WEAK_SUFFIX_NAPI
#include "weak_napi_undefs.h"
#endif
```

After the native code is ready, compile it into the host app or into a desktop
native library that the host can load. See [Native Libraries and
Autolink](/next/guide/autolink.md?platform=lynxtron) for how to distribute the library
and wire it into a Lynxtron host. Once the library is loaded, the static
registration exposes `NativeLocalStorageModule` through `NativeModules`, so a
Lynx page can call it directly:

```ts title="src/App.tsx"
NativeModules.NativeLocalStorageModule.setStorageItem('language', 'JavaScript');
NativeModules.NativeLocalStorageModule.getStorageItem('language', (value) => {
  console.log(value); // 'JavaScript'
});
```

If the same desktop native library also exposes a custom Element, see the
[Desktop platform section of Custom Element](/next/guide/custom-native-component.md?platform=desktops).

Congratulations! You have successfully created a native module. If you want to create a native module in your application, you first need to integrate Lynx by referring to the [Integrate with Existing Apps](/next/guide/start/integrate-with-existing-apps.md) guide, and then follow the steps above to create the native module.

## Type Mapping Table

| TypeScript    | iOS(Objective-C)                                  | Android(Java)                                     | HarmonyOS(ets) | Weak Node-API                     |
| ------------- | ------------------------------------------------- | ------------------------------------------------- | -------------- | --------------------------------- |
| `null`        | `nil`                                             | `null`                                            | `null`         | `Napi::Value` / `env.Null()`      |
| `undefined`   | `nil`                                             | `null`                                            | `undefined`    | `Napi::Value` / `env.Undefined()` |
| `boolean`     | `BOOL` (or `NSNumber` when used inside objects)   | `boolean` (or `Boolean` when used inside objects) | `boolean`      | `Napi::Boolean`                   |
| `number`      | `double` (or `NSNumber` when used inside objects) | `double` (or `Number` when used inside objects)   | `number`       | `Napi::Number`                    |
| `string`      | `NSString`                                        | `String`                                          | `string`       | `Napi::String`                    |
| `BigInt`      | `NSString`                                        | `long` (or `Number` when used inside objects)     | `BigInt`       | `Napi::BigInt`                    |
| `ArrayBuffer` | `NSData`                                          | `byte[]`                                          | `Buffer`       | `Napi::ArrayBuffer`               |
| `object`      | `NSDictionary`                                    | `com.lynx.react.bridge.ReadableMap`               | `object`       | `Napi::Object`                    |
| `array`       | `NSArray`                                         | `com.lynx.react.bridge.ReadableArray`             | `array`        | `Napi::Array`                     |
| `function`    | block `void (^)(id)`                              | `com.lynx.react.bridge.Callback`                  | `function`     | `Napi::Function`                  |

## Native Module Permission Verification (Experimental)

Starting from Lynx SDK 3.5, developers can use `LynxViewBuilder` to set a native module validator for the current `LynxView`, thereby controlling all native module calls within the `LynxView`. Currently, this feature is only supported on Android and iOS, with HarmonyOS support to be added in the future.


iOSAndroid

When creating a `LynxView` using `LynxViewBuilder`, register a native module validator through the `registerModuleAuthValidator` interface. The validator will apply to all native module calls within the current `LynxView`.
**Native Module Validator Interface**
```java title=""

/**
* LynxMethod verification interface, used to verify whether the LynxMethod is allowed to be
* called
*/
public interface AuthValidator {
/**
 *
 * @param moduleName The name of the called native module
 * @param methodName The name of the called native module method
 * @param methodParams The parameters of the called native module method
 * @return
 * true: Verification passed, the native module call will be executed
 * false: Verification failed, the native module call will not be executed, and a JS error will be generated
 */
boolean verify(String moduleName, String methodName, JavaOnlyArray methodParams);
}

```
**Native Module Validator Registration Method**
```java title=""

LynxViewBuilder builder = LynxView.builder()
// Register the validator instance with LynxViewBuilder
.registerModuleAuthValidator(new LynxModule.AuthValidator() {
void validate(@NonNull String moduleName, @NonNull String moduleName, @NonNull ReadableMap params) {
//Validation logic
return result;
}
}
LynxView view = builder.build(context);

```

When creating a `LynxView` using `LynxViewBuilder`, register a native module validator through the `registerMethodAuth` interface. The validator will apply to all native module calls within the current `LynxView`.
**Native Module Validator Interface**
```objective-c title=""

/**
*
* @param method: The name of the called native module method
* @param module: The called native module
* @param invoke_session: The timestamp of the native module call
* @param inv：The dynamic invocation method for this call
* @return
* true: Verification passed, the native module call will be executed
* false: Verification failed, the native module call will not be executed, and a JS error will be generated
*/
typedef BOOL (^LynxMethodBlock)(NSString *method, NSString *module, NSString *invoke_session,
NSInvocation *inv);

```
**Native Module Validator Registration Method**
```objective-c title=""

// Register the validator instance with LynxViewBuilder
LynxViewBuilder *builder = GetLynxViewBuilder();
[builder.config registerMethodAuth:validtorBlock];

```
