Skip to content
Projects

JoaoPauloCMarra/react-native-nitro-markdown

View on GitHub

About

High-performance Markdown parser for React Native using Nitro Modules and md4c

Web & App Development

How these counts are measured

Measured star growth

in 24h
0
in 7 days
+1
in 15 days
+1
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original

react-native-nitro-markdown

npm version npm downloads CI license React Native Expo Nitro Modules TypeScript

A native Markdown engine for React Native. Native C++ parsing for CommonMark and GitHub Flavored Markdown, real React Native rendering, first-class streaming for LLM/chat output, and a headless AST API — powered by md4c and Nitro Modules.

Nitro Markdown rendering rich GitHub Flavored Markdown natively in React Native The same Markdown rendered with the built-in dark theme — fully customizable themes, per-node styles, and renderers

Benchmark comparing the Nitro C++ parser with JavaScript markdown parsers Streaming token-by-token markdown for LLM and chat output GitHub Flavored Markdown tables and task lists rendered natively

Why Nitro Markdown?

Most React Native Markdown libraries parse in JavaScript on the JS thread. Nitro Markdown parses in a native C++ engine over JSI, then renders flexible React Native components — giving you a native parser boundary with component flexibility.

  • ⚡ Native C++ parsing — CommonMark + GFM with a benchmark harness so you can measure parsing and rendering on your target device (benchmarks).
  • 🔀 Streaming — built for token-by-token LLM / chat output.
  • 🧩 Headless AST — parse without UI for search, validation, indexing.
  • 🎨 Real components — theme, override per node, or swap whole renderers.
  • 📜 Virtualization — bounded memory and fast first screen on long docs.
  • 📊 GFM tables, task lists, inline & block math, syntax highlighting built in (LaTeX drawing through the optional /math subpath).
  • 🛡️ Type-safe — full TypeScript types for nodes, renderers, options.
  • 🔒 Safe by default — bounded parse input (default 10 MiB UTF-8 bytes, overridable via options.maxInputLength), a hard C++ cap, seeded fuzzing and a CommonMark/GFM conformance corpus in the test gate, and a link/image URL policy (security policy).

Install

bun add react-native-nitro-markdown [email protected]
# Expo development build
bunx expo install react-native-nitro-markdown [email protected]
bunx expo prebuild

react-native-nitro-modules is a required peer dependency (parsing runs in native code). Expo Go cannot load Nitro modules — use a development build. Full guide: Installation.

Math rendering (optional)

Math nodes render as monospace text by default. To draw LaTeX with RaTeX, install the optional peer ratex-react-native and pass the renderers from the /math subpath:

bunx expo install [email protected]   # or: bun add [email protected]
import { Markdown } from "react-native-nitro-markdown";
import { mathRenderers } from "react-native-nitro-markdown/math";

<Markdown options={{ math: true }} renderers={mathRenderers}>
  {"Euler: $e^{i\\pi} + 1 = 0$"}
</Markdown>;

[email protected] requires React Native >=0.84 and React >=19.2. On React Native 0.77–0.83, skip it; math stays readable as monospace text. The main entry and /headless never load ratex-react-native.

Inline formulas flow inside the text, keep its style, follow the OS text size, and scale down when wider than the line. See inline math layout for the layout rules and known limits.

Expo Config

No package-specific Expo config plugin is required. After installing the package and its native peer dependencies, run expo prebuild and use an Expo development build. See the Installation guide for the Expo and bare React Native setup.

iOS static frameworks are supported with source-built React Native. After upgrading, regenerate the Expo native project or run pod install, then rebuild the app so CocoaPods applies the updated header paths.

Quick Start

import { Markdown } from "react-native-nitro-markdown";

export function Article() {
  return (
    <Markdown
      options={{ gfm: true, math: true }}
      onError={(error) => {
        console.error(error);
      }}
    >
      {"# Hello\nThis is **native** markdown."}
    </Markdown>
  );
}

Native parse failures call onError instead of rendering an empty document. Headless parseMarkdown throws; do not treat an empty AST as success. Keep product fonts and colors in an app wrapper around <Markdown>.

Streaming (LLM / chat)

import { useEffect } from "react";
import {
  MarkdownStream,
  useMarkdownSession,
} from "react-native-nitro-markdown";

type StreamingMessageProps = {
  subscribe: (onToken: (token: string) => void) => () => void;
  onError: (error: Error) => void;
};

export function StreamingMessage({
  subscribe,
  onError,
}: StreamingMessageProps) {
  const session = useMarkdownSession();

  useEffect(
    () => subscribe((token) => session.getSession().append(token)),
    [session, subscribe],
  );

  return (
    <MarkdownStream
      session={session}
      updateStrategy="raf"
      incrementalParsing
      onError={onError}
    />
  );
}

MarkdownStream batches native range updates. Plain-text and fenced-code appends take an incremental path; structural updates re-parse with stable AST node reuse. Failed updates call onError(error, "parse") and retain the last valid render. For very large initial content, pass initialParseMode="async" so the first frame renders without parsing. Pass streaming={isStreaming} to hold back a last block that has not finished arriving (a table row, an image or link line, an open $$ block) instead of showing its raw syntax, and to show inline syntax that is still open (**bold, a link whose URL is arriving) the way the finished text will. Full guide: Streaming.

Session ranges use JavaScript UTF-16 units. An index inside a surrogate pair (including emoji) is rejected with invalid_range instead of rounded. Both getTextRange() and replace() also throw invalid_range for a range that is not finite, is negative, or is reversed.

Display math fences

With options.math: true, use a standalone dollar fence for multi-line display math:

$$
x_{n+1} - x_n = 0
$$

The opening line must contain $$ with zero to three leading spaces and only spaces or tabs after it, followed by a line ending. The closing line accepts zero to three leading spaces, then exactly $$ with optional trailing spaces or tabs; it may end at EOF. Fence contents are treated as opaque math text, including blank lines and Markdown-looking lines. Inline display math such as $$x^2$$ keeps its existing behavior. Lines that are not valid standalone openers keep the existing inline Markdown behavior. A valid unclosed opener consumes its content through EOF as one math block.

Content can also sit on a fence line, as LLMs often write it:

$$z = x^2 + 2y^2
$$

$$
x^2 + 2y^2 = 2$$

A line that ends with $$ closes the block, and the content before $$ is the last line of the formula. The $$ must not follow another $ or a backslash, and no other $$ may be on that line. A line that starts with $$ and holds content opens a block only when a closing line comes before the next blank line; such a block also ends at a blank line, so a stray $$5 stays text.

Headless parsing

import {
  parseMarkdown,
  parseMarkdownWithOptions,
  extractPlainText,
} from "react-native-nitro-markdown/headless";

const ast = parseMarkdown("# Title");
const mathAst = parseMarkdownWithOptions("Inline $x^2$", { math: true });
const text = extractPlainText("Hello **world**"); // "Hello world"

// Search / indexing: skip source offsets natively for a leaner AST.
const lean = parseMarkdownWithOptions(doc, { sourceOffsets: false });

sourceOffsets is optional. Set it to false when your headless code does not map AST nodes back to the original Markdown source, such as for search, indexing, validation, or plain-text extraction. Leave it omitted when you need source ranges for diagnostics, source maps, editor selection, annotations, or streaming/incremental AST reuse. The public headless default remains true so existing consumers keep receiving beg/end; changing that default would be a breaking AST-shape change. The ordinary string <Markdown> fast path chooses false internally when no consumer-facing AST or source ranges are needed.

Soft and hard break spans include the original LF or CRLF bytes expressed as UTF-16 indices; hard-break markers remain part of their source span.

The TypeScript return type follows the option: parseMarkdown("...") exposes required UTF-16 beg/end fields, while a literal { sourceOffsets: false } returns a node type without those fields. If an options object is typed as the broad ParserOptions, offsets remain optional in the result because the runtime value is not known to TypeScript.

Use the /headless export for AST data, plain-text extraction, indexing, or tests without rendering UI. Parser functions throw when the native module is unavailable, parsing fails, or native output is invalid; catch errors at your application boundary. The headless entry still requires an iOS or Android native runtime. Full guide: Headless.

Source AST rendering

Already have a MarkdownNode? Pass it via sourceAst to skip native parsing on render:

<Markdown sourceAst={ast}>{"# Cached AST"}</Markdown>

When sourceAst is provided, beforeParse plugins are skipped because parsing already happened. afterParse plugins and astTransform still run.

Parser AST nodes are mutable by default for compatibility with earlier releases. Public parser and consumer AST boundaries validate and clone trees so a consumer callback cannot poison another cached result. The default string render path keeps the native AST internal and skips that materialization. Public AST hooks and custom renderers continue to use the compatibility path. Pass options={{ freezeAst: true }} when a defensive immutable tree is preferred; this freezes nodes and child arrays before they reach plugins, transforms, and callbacks.

Theming & customization

Because every node renders as a real React Native component, you can restyle the whole document, tweak a single node type, or replace a renderer outright:

import { Markdown, darkMarkdownTheme } from "react-native-nitro-markdown";

// 1. Swap the whole theme — built-in dark preset (or any partial theme)
<Markdown theme={darkMarkdownTheme}>{content}</Markdown>;

// 2. Override individual node styles (layered on top of the theme)
<Markdown
  styles={{ heading: { color: "#7c3aed" }, code_block: { borderRadius: 16 } }}
>
  {content}
</Markdown>;

// 3. Replace a renderer entirely
<Markdown renderers={{ blockquote: MyCallout }}>{content}</Markdown>;

Presets: defaultMarkdownTheme, darkMarkdownTheme and minimalMarkdownTheme. stylingStrategy="minimal" uses the minimal theme as the base, while theme={minimalMarkdownTheme} merges over the default theme and keeps the default code token colors. Compose with mergeThemes. Full guide: Customization.

Common options

Prop / option Default What it does
options.gfm true Tables, strikethrough, task lists, autolinks.
options.math true Inline and block math nodes.
options.html false Preserve raw HTML nodes for custom renderers.
options.sourceOffsets true Optional source mapping. true emits per-node beg/end as JavaScript UTF-16 indices; false omits them and skips the native UTF-16 map. Headless consumers should choose false unless they need source ranges. The ordinary string render fast path chooses false automatically when safe.
options.maxInputLength 10485760 Maximum accepted input length in UTF-8 bytes. Oversized inputs fail with a typed input_too_large error instead of being parsed. Values above the hard cap are clamped. Documents inside the cap that exceed the native AST budgets (100,000 nodes) fail with input_too_complex.
options.freezeAst false Freeze parsed AST nodes and child arrays before exposing them to plugins, transforms, renderers, and callbacks.
parseCache true Reuse parsed ASTs for repeated content. The cache is scoped per <Markdown> instance (max 32 entries) and only holds documents up to 24,000 UTF-16 characters; longer documents are not cached or counted. Per-instance hit/miss/eviction counters are reported via onParseComplete's cacheStats.
sourceAst undefined Render a pre-parsed AST instead of parsing children.
onParsingInProgress undefined Deprecated compatibility callback invoked after the current parse render commits. Use onParseComplete or MarkdownStream state for new code.
onError undefined Receive parser, plugin, astTransform and highlightCode failures as (error, phase, pluginName?); transform and highlighter failures use phase "transform". Native parse and session failures are typed MarkdownErrors with stable code and source.
errorText "Error parsing markdown" Localized text rendered when parsing fails.
imageOptions undefined Image URL policy: allowedProtocols, allowedHosts, and remoteImages: "deny" to block remote image loading entirely.
highlightCode false Built-in code syntax highlighting (fixture-backed languages: JS/TS family, Python, shell).
virtualize false Virtualize top-level blocks for long documents.

See Usage for the full prop table and Customization for themes, per-node styles, custom renderers, and plugins.

Performance

Nitro Markdown optimizes the complete string → native parse → React Native render path. The default render-only path avoids public AST validation and cloning, omits source-offset serialization when it is safe, and collapses contiguous plain-text runs into fewer native Text nodes. Use virtualize for long documents so only the visible top-level blocks mount initially.

Representative development-build render measurements (mount-to-layout time; absolute values vary by device, build, and workload):

Render path iPhone 17 iOS Simulator Pixel 7 Android Emulator
Rich document (2,837 characters) 217.24 ms 291.20 ms
Long document with virtualization (13,540 characters) 150.50 ms 168.69 ms

These are development-build measurements from isolated fresh runs of the 0.12.x harness, not a release-performance guarantee. That harness stopped the clock 120 ms after layout, so each value includes a fixed 120 ms delay. The 0.13.0 harness stops the clock at layout; tap Run Benchmark in the example app for current numbers on your device.

The parser-only comparison uses isolated records on a 327,750-character (~328 KB) document. The example app measures Nitro only on the target device:

Nitro device path iPhone 17 iOS Simulator Pixel 7 Android Emulator
Offsets on 71.3 ms p50 57.0 ms p50
Offsets off 47.2 ms p50 37.6 ms p50

The JavaScript baseline is a separate Node benchmark. Each parser runs in a fresh process and the result includes its fixture hash and runtime. The latest macOS arm64 record for the 182,850-byte node-complex-markdown-v1 fixture was:

JavaScript baseline p50 p95
CommonMark.js 5.15 ms 9.20 ms
Markdown-It 8.59 ms 11.91 ms
Marked 13.52 ms 16.48 ms

Do not compare Node and device timings as a single speed ratio. With offsets disabled, Nitro's measured device round trip is about 34% faster than its compatibility path. The package's advantage is the full React Native path, native parsing without a JS parser dependency, streaming, and long-document virtualization; no universal "fastest" result should be inferred from one fixture. Reproduce device numbers by running the example app and tapping Run Benchmark, and reproduce the isolated JS baseline with bun run benchmark:compare. Methodology and the full capability matrix: Comparison & benchmarks.

Security

  • Parse input is bounded: the JavaScript boundary rejects documents above options.maxInputLength (default 10 MiB UTF-8 bytes) with a typed error, and the C++ parser enforces the same hard cap in bytes plus AST budgets and a 64 MiB JSON output cap (input_too_complex). Session buffers use the same UTF-8 byte cap.
  • maxInputLength is the only hard bound on synchronous parse work. Set it to the largest document your app expects, especially on low-end devices. MarkdownStream batches updates and reuses AST nodes, but each batch parses the full buffer; for large initial content use initialParseMode="async". In the C++ tests, 16 pathological input classes (six at the 10 MB cap) produced at most 1.34 parser callbacks per input byte, and the AST is capped at 100,000 nodes. The vendored md4c scanner itself is not instrumented.
  • Custom onLinkPress handlers receive the original, unvalidated href so apps can handle routes and custom schemes. Handle only links you recognize and return false for them; return true or nothing to let the built-in fallback open the link. The fallback opens only validated HTTP(S), mail, telephone and SMS URLs. Do not pass an untrusted href to Linking.openURL yourself without checking its scheme. Remote images load by default for compatibility — set imageOptions={{ remoteImages: "deny" }} (and/or allowedHosts) when rendering untrusted markdown in privacy- or SSRF-sensitive apps. Host allowlists compare complete normalized hostnames, including bracketed IPv6 addresses; ports do not change the hostname. An explicit imageOptions={{ allowedHosts: [] }} denies every image host. Omit allowedHosts to retain the default host policy, or list the permitted hosts. Migration from 0.13.x: replace an empty list with an omitted property if you intended to allow all hosts supported by the protocol policy. Malformed authorities and backslash-based URL parser ambiguities are rejected.
  • The C++ parser is fuzzed with a seeded, deterministic corpus and checked against a CommonMark/GFM conformance corpus in bun run check.

See SECURITY.md for supported versions and how to report issues.

API

The stable component, hook, headless, renderer, session, and TypeScript export surface is documented in the API reference.

Error Contract

Parser, extraction, session, and render failures use MarkdownError with stable code and source fields. A supplied or transformed AST with cyclic children fails with code: "invalid_ast" and source: "render"; return a new tree instead of mutating or cyclically linking an AST. See the API reference for the error-code contract.

Documentation

Guide What's inside
Installation Expo & bare RN setup, requirements, platforms.
Usage <Markdown>, props, elements, virtualization, source AST.
Streaming Token-by-token LLM / chat rendering.
Headless Parse to AST, plain-text extraction.
Customization Themes, dark mode, per-node styles, renderers, plugins.
Comparison & benchmarks Why Nitro, parse benchmarks, capability matrix.
API reference Full export and type listing.
Native libraries md4c and the streaming JSON writer; rejected replacements.
Security policy Supported versions, link/image policy, reporting.
Changelog Package changes and migration requirements by version.
Troubleshooting Common install and runtime issues.

Platform Support

Dependency Supported
React Native >=0.77 (New Architecture; Nitro 0.37 minimum). Tested on 0.88.1; RN 0.87 Strict TypeScript compatibility check
Expo SDK >=53 development builds. Tested on SDK 58 (58.1.0, RN 0.88.1)
Nitro Modules >=0.37.0 <0.38.0
RaTeX React Native Optional, only for react-native-nitro-markdown/math. 0.1.16 needs RN >=0.84 and React >=19.2
iOS The app's React Native iOS floor (min_ios_version_supported, 15.1 on RN 0.77–0.88)
Android minSdkVersion 24
Platforms iOS, Android (Web not supported)

Supports React Native >= 0.77 / Expo SDK >= 53 (the Nitro Modules 0.37 minimum); tested on React Native 0.88.1 / Expo SDK 58. check:ci also compiles the public source against React Native 0.87.0's Strict TypeScript API. Do not override the React Native version selected by Expo.

Web and Expo Go are not supported runtime targets because the parser requires Nitro Modules (JSI). See the installation platform matrix.

Upgrading from 0.17.x

Version 0.18.0 renders inline math inside the text around it:

  1. If you use react-native-nitro-markdown/math, install [email protected] or later.
  2. styles.text now applies to paragraphs too. Move margins, padding or a background in it to styles.paragraph.
  3. A paragraph with an inline formula renders as a Text, not a row of views. Update snapshot tests of that tree.
  4. A custom math_inline renderer is drawn on the text line. Do not give the view it returns a full width or block layout.

Upgrading from 0.12.x

Version 0.13.0 moves RaTeX math rendering to an optional subpath:

  1. If you render math with RaTeX, keep ratex-react-native installed and pass renderers={mathRenderers} (from react-native-nitro-markdown/math) to every <Markdown> and <MarkdownStream> that shows math. Spread mathRenderers into your own renderers object when you have one.

  2. If you do not need LaTeX drawing, you can uninstall ratex-react-native; math renders as monospace text.

  3. If you switch on error codes, handle the new input_too_complex code. Documents that exceed the native AST budgets used to report parse_failed.

  4. Session buffers are now capped at 10,485,760 UTF-8 bytes instead of UTF-16 units, and the error message says bytes.

  5. The React Native peer floor is now >=0.77 (Expo SDK >=53), the minimum that react-native-nitro-modules 0.37 compiles against.

  6. The default code token palette is now a light palette. If you use a custom dark theme that sets codeBackground but not every codeTokenColors entry, add the dark palette explicitly:

    import { darkMarkdownTheme } from "react-native-nitro-markdown";
    
    const theme = {
      colors: {
        codeBackground: "#111827",
        codeTokenColors: darkMarkdownTheme.colors.codeTokenColors,
      },
    };
    

Upgrading from 0.11.x and earlier

Version 0.12.0 requires react-native-nitro-modules >=0.37.0 <0.38.0. Upgrade that peer dependency before installing this package and rebuild native projects. options.maxInputLength is measured in UTF-8 bytes, and session ranges that split a UTF-16 surrogate pair now fail with invalid_range; use code-point boundaries when calling getTextRange() or replace(). The deprecated onParsingInProgress callback remains available, and ASTs are mutable by default again. Use options.freezeAst for defensive immutability.

Troubleshooting

For native-module, Expo, parser, streaming, and renderer failures, use the Troubleshooting guide. Prebuild and rebuild after native dependency changes; a successful typecheck or build does not prove runtime behavior.

Development

bun install
bun run check
bun run check:ci
bun run release:preflight

bun run example:prebuild -- --platform android
bun run example:prebuild -- --platform ios
bun run example:android:assemble
bun run example:ios:build

bun run example:smoke
bun run example:smoke:android
bun run example:smoke:ios

check validates replay freshness and helper tests, then runs package lint, typecheck (including test files), JS tests, C++ tests, and script tests. check:ci is the single CI gate: it adds version alignment, the harness (codegen check, public types, size budgets, coverage, C++ coverage), React Native 0.87 type compatibility, C++ sanitizers and the package audit; it does not launch a native app. release:preflight adds example checks and an auth-free pack check; it does not publish or release the package. Prebuild generates native projects, the Android/iOS build commands compile them, and smoke commands are the runtime checks. Build and self-check success alone is not runtime proof.

The smoke report counts only rendered-content checks as proof for a platform. The iOS smoke run captures a screenshot but cannot assert rendered content yet, so example:smoke:ios fails unless you pass --allow-skip (bun scripts/example-smoke.js --ios --allow-skip); use the agent-device replay flows below for iOS content checks.

Use bun run example:replay --platform ios --udid <exact-target> or --platform android --serial <exact-target> for the maintained agent-device flows. The example must already be installed from the source under test. After reviewing package or example changes, update affected coverage assertions and run bun run example:replay:refresh; bun run example:replay:check rejects stale coverage. The contracts-http flow also needs --http-fixture-url and the local image fixture. See the replay guide for suite selection, prerequisites, and limits on what each flow proves.

When several devices are available, set ANDROID_SERIAL for Android and EXAMPLE_SMOKE_IOS_UDID for iOS. The iOS smoke check stops if it cannot select one booted simulator.

Example app build speed

The example app is generated (Expo CNG), so build settings live in tracked config: apps/example/app.config.js and apps/example/plugins/with-fast-gradle.js. They apply on the next example:prebuild.

Setting Where Default Override
Gradle build cache and parallel projects (org.gradle.caching, org.gradle.parallel) with-fast-gradle.js on edit the plugin, or pass --no-build-cache / --no-parallel to Gradle
Gradle and Kotlin daemon memory (-Xmx6g, kotlin.daemon.jvmargs=-Xmx3g) with-fast-gradle.js on lower the values on hosts with less than 16 GB
Android ABIs (buildArchs) app.config.js all four ABIs, so release APKs run on phones NITRO_ANDROID_ARCHS=x86_64 bun run example:prebuild -- --platform android builds an emulator-only app; use comma-separated values for several ABIs
iOS ccache (ios.ccacheEnabled) app.config.js on install it with brew install ccache; see React Native local caches

The Gradle configuration cache stays off because example:android:assemble runs with --no-configuration-cache. useFrameworks and the prebuilt React Native core are unchanged.

Contributing

bun install
bun run check          # lint + typecheck + tests
bun run example:ios    # run the example app

See CONTRIBUTING.md. Run native example builds locally before release when changing native, Nitro, rendering, or packaging files. GitHub CI does not build the Android or iOS example.

License

MIT

Explore related projects

Loading…