# hashicorp/next-mdx-remote architecture

> Architecture diagram of the GitHub repository hashicorp/next-mdx-remote, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hashicorp/next-mdx-remote
- Repository: https://github.com/hashicorp/next-mdx-remote

## Overview

##### Project Type and Purpose
- Type: Open-source utility library (npm package) for Next.js.
- Purpose:
– Provide a `serialize` API to compile raw MDX into a serializable payload during Next.js data-fetching phase (`getStaticProps` / `getServerSideProps`).
– Provide an `<MDXRemote />` React component to hydrate/ render that payload in the browser.
– Support RSC via `next-mdx-remote/rsc` with `compileMdx` and an async `<MDXRemote />`.

##### File Structure
- Entry points:
– `index.js` + `serialize.js` (CJS for Browser/Server)
– `rsc.js` (RSC entrypoint)
- Core source (in `src/`):
– `serialize.ts` – implements `serialize()` (server).
– `rsc.tsx` – implements RSC APIs (`compileMdx`, RSC `<MDXRemote/>`).
– `index.tsx` – re-exports main APIs.
– `plugins/` – transforms (e.g., remove imports/exports).
– `format-mdx-error.ts`, `idle-callback-polyfill.js`, `jsx-runtime.cjs` – internal helpers.
- Tests live under `__tests__/…` to validate both classic and RSC flows.
- Config files define CI, TypeScript, linting, publishing.

##### Extract Architectural Insights from the README
- Two-phase separation:
– **Server-side**: `serialize(source, options)` → compiles MDX (using MDX core, remark/rehype plugins, optional frontmatter).
– **Client-side**: `<MDXRemote {...serialized} components={…} lazy?>` → hydrates and renders.
- RSC support:
– `compileMdx({ source, options })` → returns `{ content, frontmatter }`.
– RSC `<MDXRemote source components?>` → server-component rendering.
- Emphasized code-splitting safety in Next.js.

##### Main Components and Data Flows
A. Next.js Server (Build or Request Phase)
1. getStaticProps / getServerSideProps
2. Calls `serialize(source, { mdxOptions, scope, parseFrontmatter })`
3. Internally invokes MDX compiler + remark/rehype plugins + vfile-matter frontmatter parser
4. Outputs `MDXRemoteSerializeResult` (JSON-serializable)
5. Next.js sends this payload in page props to the client

B. Browser / Client Runtime
1. React application mounting
2. `<MDXRemote {...serialized} components={…} />`
3. Under the hood:
– Uses `new Function(compiledSource)` from `jsx-runtime.cjs` to reconstruct React elements
– Hydrates those elements in the DOM
4. Optional lazy hydration (`lazy` prop uses an idle-callback polyfill to defer hydration)

C. React Server Components Flow (Next.js 13+ App Directory)
1. Server Component calls `compileMdx({ source, options })` from `next-mdx-remote/rsc`
2. Receives `{ content, frontmatter }`
3. RSC `<MDXRemote source content frontmatter components?>`
4. Streams rendered React Server Component output to the client

D. Plugin Subsystem
– `src/plugins/remove-imports-exports.ts` hooks into MDX compilation pipeline to strip unsupported MDX imports/exports.
– Additional remark/rehype plugins can be passed via `mdxOptions`.

##### Architectural Patterns & Principles
- “Separation of Concerns”: server compile vs. client render vs. RSC render.
- Plugin pipeline: MDX compiler is extensible.
- Tree-shaking/code-splitting: Next.js removes server-only code from client bundle if entrypoint usage is localized.
- Dual entrypoints (CJS/ESM) for compatibility with Next.js bundlers (webpack, Turbopack).

##### Technologies / Frameworks
– Next.js (data-fetching API, RSC)
– MDX core (`@mdx-js/mdx`)
– remark & rehype plugin ecosystem
– React & React Server Components
– TypeScript (for types and safety)
– Babel/Webpack/Turbopack (affected via `next.config.js`)

## Diagram (Mermaid)

```mermaid
flowchart TB
  %% Next.js Server Side
  subgraph "Next.js Server (Build/Request Phase)"
    direction TB
    GS["getStaticProps / getServerSideProps"]:::server
    SerializeAPI["serialize() API"]:::server
    CJSIndex["CommonJS Entry (index.js)"]:::server
    GS -->|"calls serialize()"| SerializeAPI
    CJSIndex
    click CJSIndex "https://github.com/hashicorp/next-mdx-remote/blob/main/index.js"
    click SerializeAPI "https://github.com/hashicorp/next-mdx-remote/blob/main/serialize.js"
    %% MDX Compiler Subsystem
    subgraph "MDX Compiler" 
      direction TB
      MDXCore["@mdx-js/mdx, remark/rehype"]:::external
      VFile["vfile-matter"]:::external
      SerializeImpl["serialize.ts"]:::server
      DefSerialize["serialize.d.ts"]:::server
      Plugins["remove-imports-exports.ts"]:::server
      FormatError["format-mdx-error.ts"]:::server
      Types["types.ts"]:::server
      MDXCore --> SerializeImpl
      VFile --> SerializeImpl
      Plugins --> SerializeImpl
      SerializeImpl --> DefSerialize
      SerializeImpl --> FormatError
      SerializeImpl --> Types
      click SerializeImpl "https://github.com/hashicorp/next-mdx-remote/blob/main/src/serialize.ts"
      click DefSerialize "https://github.com/hashicorp/next-mdx-remote/blob/main/serialize.d.ts"
      click Plugins "https://github.com/hashicorp/next-mdx-remote/blob/main/src/plugins/remove-imports-exports.ts"
      click FormatError "https://github.com/hashicorp/next-mdx-remote/blob/main/src/format-mdx-error.ts"
      click Types "https://github.com/hashicorp/next-mdx-remote/blob/main/src/types.ts"
    end
    SerializeAPI -->|"compiles MDX"| MDXCore
    MDXCore -->|"returns MDXRemoteSerializeResult"| Payload
  end

  %% Serialized Payload
  Payload["MDXRemoteSerializeResult (JSON)"]:::server

  %% Browser / Client Runtime
  subgraph "Browser / Client React Runtime"
    direction TB
    MDXRemoteCSR["<MDXRemote /> Hydration"]:::client
    JSXRuntime["jsx-runtime.cjs"]:::client
    IdlePolyfill["idle-callback-polyfill.js"]:::client
    DOM["React DOM"]:::client
    Payload -->|"passed as props"| MDXRemoteCSR
    MDXRemoteCSR -->|"uses new Function"| JSXRuntime
    MDXRemoteCSR -->|"lazy?"| IdlePolyfill
    MDXRemoteCSR -->|"renders to"| DOM
    click MDXRemoteCSR "https://github.com/hashicorp/next-mdx-remote/blob/main/src/index.tsx"
    click JSXRuntime "https://github.com/hashicorp/next-mdx-remote/blob/main/src/jsx-runtime.cjs"
    click IdlePolyfill "https://github.com/hashicorp/next-mdx-remote/blob/main/src/idle-callback-polyfill.js"
  end

  %% React Server Components Flow
  subgraph "React Server Components Flow"
    direction TB
    AppServer["Next.js App Server Component"]:::server
    RSCEntrypoint["RSC CJS Entry (rsc.js)"]:::rsc
    CompileRSC["compileMdx()"]:::rsc
    RSCMDXRemote["RSC <MDXRemote />"]:::rsc
    AppServer -->|"calls compileMdx()"| RSCEntrypoint
    RSCEntrypoint --> CompileRSC
    CompileRSC --> RSCMDXRemote
    RSCMDXRemote -->|"streams rendered output"| DOM
    click RSCEntrypoint "https://github.com/hashicorp/next-mdx-remote/blob/main/rsc.js"
    click CompileRSC "https://github.com/hashicorp/next-mdx-remote/blob/main/src/rsc.tsx"
  end

  %% Tests and Typings
  Tests["__tests__ (unit & integration)"]:::external
  Typings["Package Typings (index.d.ts)"]:::server
  click Tests "https://github.com/hashicorp/next-mdx-remote/tree/main/__tests__/"
  click Typings "https://github.com/hashicorp/next-mdx-remote/blob/main/index.d.ts"

  %% External Dependencies
  subgraph "External Dependencies"
    direction TB
    MDXCore
    VFile
    React["React"]:::external
  end

  style GS fill:#D0E7FF,stroke:#0366D6
  style SerializeAPI fill:#D0E7FF,stroke:#0366D6
  style CJSIndex fill:#D0E7FF,stroke:#0366D6
  style Payload fill:#D0E7FF,stroke:#0366D6

  style MDXCore fill:#E1E4E8,stroke:#959DA5,stroke-dasharray: 2 2
  style VFile fill:#E1E4E8,stroke:#959DA5,stroke-dasharray: 2 2
  style React fill:#E1E4E8,stroke:#959DA5,stroke-dasharray: 2 2
  style Tests fill:#E1E4E8,stroke:#959DA5,stroke-dasharray: 2 2

  style SerializeImpl fill:#FFD8A8,stroke:#D29922
  style Plugins fill:#FFD8A8,stroke:#D29922
  style FormatError fill:#FFD8A8,stroke:#D29922
  style DefSerialize fill:#FFD8A8,stroke:#D29922
  style Types fill:#FFD8A8,stroke:#D29922

  style MDXRemoteCSR fill:#D4F5D4,stroke:#2E8B57
  style JSXRuntime fill:#D4F5D4,stroke:#2E8B57
  style IdlePolyfill fill:#D4F5D4,stroke:#2E8B57
  style DOM fill:#D4F5D4,stroke:#2E8B57

  style AppServer fill:#D0E7FF,stroke:#0366D6
  style RSCEntrypoint fill:#E5D4FA,stroke:#8A2BE2
  style CompileRSC fill:#E5D4FA,stroke:#8A2BE2
  style RSCMDXRemote fill:#E5D4FA,stroke:#8A2BE2

  classDef server fill:#D0E7FF,stroke:#0366D6
  classDef client fill:#D4F5D4,stroke:#2E8B57
  classDef rsc fill:#E5D4FA,stroke:#8A2BE2
  classDef external fill:#E1E4E8,stroke:#959DA5,stroke-dasharray:2 2
```
