Showing preview only (299K chars total). Download the full file or copy to clipboard to get everything.
Repository: ipikuka/next-mdx-remote-client
Branch: main
Commit: 2bf52150eb4d
Files: 64
Total size: 281.1 KB
Directory structure:
gitextract_yhdnptxl/
├── .editorconfig
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ ├── main.yml
│ └── publish.yml
├── .gitignore
├── .npmignore
├── .npmrc
├── .prettierignore
├── .prettierrc.json
├── LICENSE
├── README.md
├── codecov.yml
├── eslint.config.js
├── migration_guide.md
├── package.json
├── src/
│ ├── csr/
│ │ ├── MDXClient.tsx
│ │ ├── MDXClientAsync.tsx
│ │ ├── MDXClientLazy.tsx
│ │ ├── hydrate.tsx
│ │ ├── hydrateAsync.tsx
│ │ ├── hydrateLazy.tsx
│ │ ├── idle-callback-polyfill.js
│ │ ├── index.ts
│ │ ├── requestIdleCallback.d.ts
│ │ ├── serialize.ts
│ │ └── types.ts
│ ├── lib/
│ │ ├── compile.ts
│ │ ├── prepare.ts
│ │ ├── run.ts
│ │ ├── types.ts
│ │ └── util.ts
│ ├── rsc/
│ │ ├── MDXRemote.tsx
│ │ ├── evaluate.tsx
│ │ ├── index.ts
│ │ └── types.ts
│ └── utils/
│ ├── getFrontmatter.ts
│ └── index.ts
├── tests/
│ ├── ErrorBoundaryClassic.jsx
│ ├── ErrorBoundaryForTests.tsx
│ ├── context/
│ │ ├── ExampleForm.mjs
│ │ ├── ExampleFormTransformedAutomatic.mjs
│ │ ├── ExampleFormTransformedClassic.mjs
│ │ ├── HelloDave.mjs
│ │ ├── components.js
│ │ └── data.js
│ ├── test.MDXClient.spec.tsx
│ ├── test.MDXClientAsync.esm.spec.tsx
│ ├── test.MDXClientLazy.spec.tsx
│ ├── test.MDXProvider.spec.tsx
│ ├── test.MDXRemote.esm.spec.tsx
│ ├── test.MDXRemote.spec.tsx
│ ├── test.compile.spec.tsx
│ ├── test.core.spec.ts
│ ├── test.evaluate.esm.spec.tsx
│ ├── test.evaluate.spec.tsx
│ ├── test.original.compile.spec.tsx
│ ├── test.run.spec.tsx
│ ├── test.serialize-hydrate.spec.tsx
│ ├── test.utils.spec.ts
│ ├── test.wrapper.spec.tsx
│ └── utils/
│ └── index.ts
├── tsconfig.json
├── vite.config.js
└── vitest-setup-tests.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
# Stop the editor from looking for .editorconfig files in the parent directories
root = true
[*]
# Non-configurable Prettier behaviors
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
# Configurable Prettier behaviors
end_of_line = lf
indent_style = space
indent_size = 2
max_line_length = 96
[*.md]
trim_trailing_whitespace = false
max_line_length = off
================================================
FILE: .github/FUNDING.yml
================================================
github: [ipikuka]
================================================
FILE: .github/workflows/main.yml
================================================
name: main
on:
pull_request:
branches:
- "**"
push:
branches:
- "**"
jobs:
test:
name: Test (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: [20, 22, 24]
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node ${{ matrix.node }}
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node }}
cache: npm
- run: npm ci
- run: npm test
- run: npm run format
coverage:
name: Code Coverage (Node 22)
needs: test
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node 22
uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run test-coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
directory: ./coverage/
files: ./coverage.json
fail_ci_if_error: true
verbose: true
token: ${{ secrets.CODECOV_TOKEN }}
slug: ipikuka/next-mdx-remote-client
================================================
FILE: .github/workflows/publish.yml
================================================
name: publish to npm
on:
release:
types: [published]
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # for provenance
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Node 22
uses: actions/setup-node@v6
with:
node-version: 22
registry-url: https://registry.npmjs.org/
cache: npm
- run: npm ci
- run: npm run build
- run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
================================================
FILE: .gitignore
================================================
.DS_Store
.vscode
dist
node_modules
archive
coverage
================================================
FILE: .npmignore
================================================
dist/*.tsbuildinfo
================================================
FILE: .npmrc
================================================
ignore-scripts=true
================================================
FILE: .prettierignore
================================================
.DS_Store
.vscode
dist
node_modules
package-lock.json
archive
coverage
README.md
migration_guide.md
================================================
FILE: .prettierrc.json
================================================
{
"singleQuote": false,
"bracketSpacing": true,
"trailingComma": "all",
"tabWidth": 2,
"useTabs": false,
"semi": true,
"arrowParens": "always",
"endOfLine": "lf",
"printWidth": 96,
"objectWrap": "preserve"
}
================================================
FILE: LICENSE
================================================
# Mozilla Public License Version 2.0
Copyright (c) 2026 @talatkuyuk AKA @ipikuka
1. Definitions
---
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
---
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
---
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
---
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
---
- *
- 6. Disclaimer of Warranty \*
- ------------------------- \*
- *
- Covered Software is provided under this License on an "as is" \*
- basis, without warranty of any kind, either expressed, implied, or \*
- statutory, including, without limitation, warranties that the \*
- Covered Software is free of defects, merchantable, fit for a \*
- particular purpose or non-infringing. The entire risk as to the \*
- quality and performance of the Covered Software is with You. \*
- Should any Covered Software prove defective in any respect, You \*
- (not any Contributor) assume the cost of any necessary servicing, \*
- repair, or correction. This disclaimer of warranty constitutes an \*
- essential part of this License. No use of any Covered Software is \*
- authorized under this License except under this disclaimer. \*
- *
---
---
- *
- 7. Limitation of Liability \*
- -------------------------- \*
- *
- Under no circumstances and under no legal theory, whether tort \*
- (including negligence), contract, or otherwise, shall any \*
- Contributor, or anyone who distributes Covered Software as \*
- permitted above, be liable to You for any direct, indirect, \*
- special, incidental, or consequential damages of any character \*
- including, without limitation, damages for lost profits, loss of \*
- goodwill, work stoppage, computer failure or malfunction, or any \*
- and all other commercial damages or losses, even if such party \*
- shall have been informed of the possibility of such damages. This \*
- limitation of liability shall not apply to liability for death or \*
- personal injury resulting from such party's negligence to the \*
- extent applicable law prohibits such limitation. Some \*
- jurisdictions do not allow the exclusion or limitation of \*
- incidental or consequential damages, so this exclusion and \*
- limitation may not apply to You. \*
- *
---
8. Litigation
---
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
---
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
================================================
FILE: README.md
================================================
**A robust Next.js newsletter `Next.js Weekly` is sponsoring me** 💖
[](https://nextjsweekly.com/)
### [Become a sponsor](https://github.com/sponsors/ipikuka/) 🚀
If you find **`next-mdx-remote-client`** useful in your projects, consider supporting my work.
Your sponsorship means a lot 💖
My sponsors are going to be featured here and on [my sponsor wall](https://github.com/sponsors/ipikuka).
A warm thanks 🙌 to [@ErfanEbrahimnia](https://github.com/ErfanEbrahimnia), [@recepkyk](https://github.com/recepkyk), and [@LSeaburg](https://github.com/LSeaburg) for the support!
Thank you for supporting open source! 🙌
# next-mdx-remote-client
[![npm version][badge-npm-version]][url-npm-package]
[![npm downloads][badge-npm-download]][url-npm-package]
[![publish to npm][badge-publish-to-npm]][url-publish-github-actions]
[![code-coverage][badge-codecov]][url-codecov]
[![type-coverage][badge-type-coverage]][url-github-package]
[![typescript][badge-typescript]][url-typescript]
[![license][badge-license]][url-license]
**`next-mdx-remote-client`** is recommended in the [`Next.js` official documentation](https://nextjs.org/docs/15/app/guides/mdx#remote-mdx).
> [!IMPORTANT]
> **If you are using `react18`, use ver.1 of `next-mdx-remote-client`, currently `v1.1`**
>
> **If you are using `react19`, use ver.2 of `next-mdx-remote-client`, currently `v2.1`**
>
> *The both serve the same features and APIs. I am going to maintain both.*
**`next-mdx-remote-client`** is a wrapper of **`@mdx-js/mdx`** for **`nextjs`** applications in order to load MDX content. It is a fork of **`next-mdx-remote`**.
See some blog applications in which **`next-mdx-remote-client`** is used:
+ for a **`app` router demo application** visit [source code](https://github.com/talatkuyuk/next-mdx-remote-client-in-app-router) or [living web site](https://nmrc-in-app-router.vercel.app/),
+ for a **`pages` router demo application** visit [source code](https://github.com/talatkuyuk/next-mdx-remote-client-in-pages-router) or [living web site](https://nmrc-in-pages-router.vercel.app/),
+ for a **testing application** which uses **both `app` and `pages` router**, visit [source code](https://github.com/talatkuyuk/testing-app-for-next-mdx-remote-client) or [living web site](https://testing-app-for-nmrc.vercel.app/).
## Why `next-mdx-remote-client` ?
I started to create **`next-mdx-remote-client`** in line with the mindset of **`@mdx-js/mdx`** in early 2024 considering **`next-mdx-remote`** had not been updated for a long time, and finally, a brand new package emerged.
**`next-mdx-remote-client`** serves as a **viable alternative** to **`next-mdx-remote`** having **more features**.
**I would like to highlight some main features:**
+ It supports MDX version 3.
+ It provides well designed components and functions for both "pages" router and "app" router, which completely isolated from eachother.
+ It provides internal error handling mechanism.
+ It supports `import statements` and `export statements` in MDX source, which can be disabled as well.
+ Creating table of contents (TOC) is so easy since it supports passing `vfile.data` into the `scope`.
+ You can get frontmatter without compiling the source for example for listing articles/posts via `getFrontmatter`.
+ It exports some components and types from `@mdx-js/mdx` so as you don't need to install.
Let's compare the features of **`next-mdx-remote`** and **`next-mdx-remote-client`**.
| Features | `next-mdx-remote` | `next-mdx-remote-client` |
| :---------------------------------------------------------- | :-----------------: | :----------------------: |
| support MDX version 3 | ✅ | ✅ |
| ensure internal error handling mechanism in `app` router | ❌ | ✅ |
| ensure internal error handling mechanism in `pages` router | ❌ | ✅ |
| support _export-from-MDX_ in `app` router | ❌ | ✅ |
| support _export-from-MDX_ in `pages` router | ❌ | ✅ |
| support _import-into-MDX_ in `app` router | ❌ | ✅ |
| support _import-into-MDX_ in `pages` router | ❌ | ❌ |
| get frontmatter and mutated scope in `app` router | ❌ | ✅ |
| get frontmatter and mutated scope in `pages` router | ✅ | ✅ |
| support options for disabling imports and exports in MDX | ✅ | ✅ |
| support passing `vfile.data` into the `scope` | ❌ | ✅ |
| provide utility for getting frontmatter without compiling | ❌ | ✅ |
| expose `MDXProvider` from `@mdx-js/mdx` | ❌ | ✅ |
| provide option for disabling parent `MDXProvider` contexts | ❌ | ✅ |
| expose the necessary types from `mdx/types` | ❌ | ✅ |
| injects `React` instance into runtime options | ❌ | ✅ |
> [!IMPORTANT]
> You will see a lot the abbreviatons **`csr`** and **`rsc`**. _Pay attention to the both are spelled backwards._\
> \
> **`csr`** stands for "client side rendering" which is related with **`pages`** router\
> **`rsc`** stands for "react server component" which is related with **`app`** router
## General considerations about development
- It is ESM only package
- Needs `react` version 19.1+, works with `next@15` and `next@16` versions (tested)
- Needs `node` version 20.9.0+ in line with `Next.js` does
- Vitest is used instead of jest for testing
- Rollup is removed for bundling
- Test coverage is 100%
- Type coverage is 100%
- The parts client side (csr) and server side (rsc) are completely isolated from each other
- Exported a small utility to get frontmatter without compiling the source
- **All functions take named parameters**
- Supports `import statements` and `export statements` in MDX
- Export statements in MDX work for **both** `app` and `pages` router
- Import statements in MDX work for **only** `app` router
> [!IMPORTANT]
> **Imported modules in MDX with relative path should be transpiled into javascript before or during build process, otherwise will not work.** I believe the community can find a solution to import reqular **`.jsx`** or **`.tsx`** modules into MDX. With the support of the **`next/mdx`**, it is viable to import **`.mdx`** into MDX, but not tested yet.
## Installation
This package is ESM only, requires Node.js (version 18.18+).
```bash
# in general
npm install next-mdx-remote-client
# specifically for react18 users
npm install next-mdx-remote-client@^1
# specifically for react19 users
npm install next-mdx-remote-client@^2
```
or
```bash
yarn add next-mdx-remote-client
```
> [!WARNING]
> **`next-mdx-remote`** users may follow the [migration guide](/migration_guide.md).
## Initial Security Concerns
Before diving into **`next-mdx-remote-client`**, it’s important to highlight the security risks associated with rendering MDX content.
Because MDX supports JavaScript expressions, it introduces serious security considerations. If the content is not fully trusted and controlled, it can enable **cross-site scripting (XSS)** attacks and even lead to **remote code execution (RCE)**. In the worst-case scenario, attackers could steal sensitive data, inject malicious scripts, install malware, or compromise your server.
> **Never render user-supplied MDX without proper sanitization.**
MDX provides three powerful constructs: **JSX syntax**, **JavaScript expressions**, and **ESM blocks (`mdxjsEsm`)** such as `import` and `export`. **`next-mdx-remote-client`** provides options to disable **ESM blocks (`mdxjsEsm`)**. However, it does **not** take responsibility for securing MDX content itself, as **it operates purely at the rendering layer**. Content sanitization and JS expression control should be handled earlier in the processing pipeline (e.g., at the remark/recma/compilation stage).
If you do not have full control over the MDX source, you should at minimum strip **dangerous JavaScript expressions** before rendering. A recommended approach is to use the remark plugin [**`remark-mdx-remove-expressions`**](https://github.com/ipikuka/remark-mdx-remove-expressions), which removes executable/dangerous MDX expressions at the syntax level.
For further security concerns you can visit [Security section](#security).
## The package's exported subpaths
The main entry point **`/`** also refers to **`/csr`** subpath.
```typescript
// main entry point, which is related "pages" router
import /* */ from "next-mdx-remote-client";
// isolated subpath for the "serialize" function
import /* */ from "next-mdx-remote-client/serialize";
// sub entry point related with "pages" router
import /* */ from "next-mdx-remote-client/csr";
// sub entry point related with "app" router
import /* */ from "next-mdx-remote-client/rsc";
// isolated subpath for the utils
import /* */ from "next-mdx-remote-client/utils";
```
## The part associated with Next.js `app` router
_Go to [the part associated with Next.js pages router](#the-part-associated-with-nextjs-pages-router)_
**`next-mdx-remote-client`** exposes **`evaluate`** function and **`MDXRemote`** component for **"app" router**.
```typescript
import { evaluate, MDXRemote } from "next-mdx-remote-client/rsc";
```
> [!TIP]
> If you need to get the **exports** from MDX --> use **`evaluate`**\
> If you don't need --> use **`MDXRemote`**\
> \
> If you need to get the **frontmatter** and the **mutated scope** --> use **`evaluate`**\
> If you don't need --> use **`MDXRemote`**
Let's give some examples how to use **`next-mdx-remote-client`** in "app" router first, then explain the exposed function and component.
### Examples for `app` router
See a **demo application** with **`app` router**, visit [source code](https://github.com/talatkuyuk/next-mdx-remote-client-in-app-router) or [living web site](https://nmrc-in-app-router.vercel.app/).
#### An example with `javascript`
```jsx
import { Suspense } from "react";
import { MDXRemote } from "next-mdx-remote-client/rsc";
import { ErrorComponent, LoadingComponent } from "../components";
import { Test } from '../mdxComponents';
const components = {
Test,
wrapper: ({ children }) => <div className="mdx-wrapper">{children}</div>,
}
export default async function Page() {
const source = "Some **bold text** in MDX, with a component <Test />";
return (
<Suspense fallback={<LoadingComponent />}>
<MDXRemote
source={source}
components={components}
onError={ErrorComponent}
/>
</Suspense>
);
};
```
#### An example with `typescript`, parsing frontmatter and providing custom data with scope
```tsx
import { Suspense } from "react";
import { MDXRemote } from "next-mdx-remote-client/rsc";
import type { MDXRemoteOptions, MDXComponents } from "next-mdx-remote-client/rsc";
import { calculateSomeHow, getSourceSomeHow } from "../utils";
import { ErrorComponent, LoadingComponent } from "../components";
import { Test } from '../mdxComponents';
const components: MDXComponents = {
Test,
wrapper: function ({ children }: React.ComponentPropsWithoutRef<"div">) {
return <div className="mdx-wrapper">{children}</div>;
},
}
export default async function Page() {
const source = await getSourceSomeHow();
if (!source) {
return <ErrorComponent error="The source could not found !" />;
}
const options: MDXRemoteOptions = {
mdxOptions: {
// ...
},
parseFrontmatter: true,
scope: {
readingTime: calculateSomeHow(source),
},
};
return (
<Suspense fallback={<LoadingComponent />}>
<MDXRemote
source={source}
options={options}
components={components}
onError={ErrorComponent}
/>
</Suspense>
);
}
```
#### An example with creating a table of contents (TOC)
I assume you have a MDX content having `<TableOfContentComponent />` inside; and you've provided it in MDX components.
```markdown
---
title: My Article
---
# {frontmatter.title}
<TableOfContentComponent toc={toc} />
rest of the article...
```
You can have a look at an example [TableOfContentComponent](https://github.com/talatkuyuk/next-mdx-remote-client-in-app-router/blob/main/mdxComponents/Toc.tsx) in the demo application.
In order to create a table of contents (TOC) I use **`remark-flexible-toc`** in the remark plugins and pass the table of contents objects `vFile.data.toc` into the `scope` via the option `vfileDataIntoScope`.
That's it! So easy!
```tsx
import { Suspense } from "react";
import { MDXRemote, type MDXRemoteOptions } from "next-mdx-remote-client/rsc";
import remarkFlexibleToc from "remark-flexible-toc"; // <---------
import { calculateSomeHow, getSourceSomeHow } from "../utils";
import { ErrorComponent, LoadingComponent } from "../components";
import { components } from '../mdxComponents';
export default async function Page() {
const source = await getSourceSomeHow();
if (!source) {
return <ErrorComponent error="The source could not found !" />;
}
const options: MDXRemoteOptions = {
mdxOptions: {
remarkPlugins: [
// ...
remarkFlexibleToc, // <---------
],
},
parseFrontmatter: true,
scope: {
readingTime: calculateSomeHow(source),
},
vfileDataIntoScope: "toc", // <---------
};
return (
<Suspense fallback={<LoadingComponent />}>
<MDXRemote
source={source}
options={options}
components={components}
onError={ErrorComponent}
/>
</Suspense>
);
}
```
#### An example with using "frontmatter" and "scope" in JSX in "app" router
```tsx
import { Suspense } from "react";
import { evaluate, type EvaluateOptions } from "next-mdx-remote-client/rsc";
import remarkFlexibleToc, { type TocItem } from "remark-flexible-toc";
import { calculateSomeHow, getSourceSomeHow } from "../utils";
import { ErrorComponent, LoadingComponent, TableOfContentComponent } from "../components";
import { components } from "../mdxComponents";
type Scope = {
readingTime: string;
toc?: TocItem[];
};
type Frontmatter = {
title: string;
author: string;
};
export default async function Page() {
const source = await getSourceSomeHow();
if (!source) {
return <ErrorComponent error="The source could not found !" />;
}
const options: EvaluateOptions<Scope> = {
mdxOptions: {
remarkPlugins: [
// ...
remarkFlexibleToc,
],
},
parseFrontmatter: true,
scope: {
readingTime: calculateSomeHow(source),
},
vfileDataIntoScope: "toc",
};
const { content, frontmatter, scope, error } = await evaluate<Frontmatter, Scope>({
source,
options,
components,
});
if (error) {
return <ErrorComponent error={error} />;
}
return (
<>
<h1>{frontmatter.title}</h1>
<p>Written by {frontmatter.author}; read in {scope.readingTime}</p>
<TableOfContentComponent toc={scope.toc} />
<Suspense fallback={<LoadingComponent />}>
{content}
</Suspense>
</>
);
}
```
Actually, you may not need to access the "frontmatter" and "scope" in JSX, you can use them within MDX directly, and return just `content` only.
```tsx
// ...
export default async function Page({ source }: Props) {
// ...
return (
<Suspense fallback={<LoadingComponent />}>
{content}
</Suspense>
);
}
```
_article.mdx_
```markdown
# {frontmatter.title}
Written by {frontmatter.author}; read in {readingTime}
<TableOfContentComponent toc={toc} />
rest of the article...
```
After the examples given, let's dive into the exposed function and component by **`next-mdx-remote-client`** for "app" router.
### The `evaluate` function
_Go to the [MDXRemote](#the-mdxremote-component) component_
The `evaluate` function is used for **compiling** MDX source, **constructing compiled source**, getting exported information from MDX and returning MDX content to be rendered on the server side, as a react server component.
```typescript
async function evaluate(props: EvaluateProps): Promise<EvaluateResult> {}
```
The `evaluate` function takes `EvaluateProps` and returns `EvaluateResult` as a promise.
**Props of the `evaluate` function**
```typescript
type EvaluateProps<TScope> = {
source: Compatible;
options?: EvaluateOptions<TScope>;
components?: MDXComponents;
};
```
**Result of the `evaluate` function**
```typescript
type EvaluateResult<TFrontmatter, TScope> = {
content: React.JSX.Element;
mod: Record<string, unknown>;
frontmatter: TFrontmatter;
scope: TScope;
error?: Error;
};
```
The `evaluate` has **internal error handling mechanism** as much as it can, in order to do so, it returns an **`error`** object if it is catched.
> [!CAUTION]
> The eval of the compiled source returns a module `MDXModule`, and does not throw errors except syntax errors. Some errors throw during the render process which needs you to use an **ErrorBoundary**.
```tsx
import { Suspense } from "react";
import { evaluate, type EvaluateOptions } from "next-mdx-remote-client/rsc";
import { ErrorComponent, LoadingComponent, TableOfContentComponent } from "../components";
import { components } from "../mdxComponents";
import type { Frontmatter, Scope } from "../types"
export default async function MDXComponent({ source }: {source?: string}) {
if (!source) {
return <ErrorComponent error="The source could not found !" />;
}
const options: EvaluateOptions = {
/* */
};
const { content, mod, frontmatter, scope, error } = await evaluate<Frontmatter, Scope>({
source,
options,
components,
});
if (error) {
return <ErrorComponent error={error} />;
}
/**
* Use "mod", "frontmatter" and "scope" as you wish
*
* "mod" object is for exported information from MDX
* "frontmatter" is available even if a MDX syntax error occurs
* "scope" is for mutated scope if the `vfileDataIntoScope` option is used
*/
return (
<>
<h1>{frontmatter.title}</h1>
<div><em>{mod.something}</em></div>
<TableOfContentComponent toc={scope.toc} />
<Suspense fallback={<LoadingComponent />}>
{content}
</Suspense>
</>
);
};
```
If you provide **the generic type parameters** like `await evaluate<Frontmatter, Scope>(){}`, the `frontmatter` and the `scope` get the types, otherwise `Record<string, unknown>` by default for both.
> [!WARNING]
> Pay attention to the order of the generic type parameters.\
> \
> The type parameters `Frontmatter` and `Scope` should extend `Record<string, unknown>`. You should use **`type`** instead of **`interface`** for type parameters otherwise, you will receive an error saying `Type 'Xxxx' does not satisfy the constraint 'Record<string, unknown>'.` See this [issue](https://github.com/ipikuka/next-mdx-remote-client/issues/2) for more explanation.
In the above example, I assume you use **`remark-flexible-toc`** remark plugin in order to collect the headings from MDX content, and you pass that information into the `scope` via `vfileDataIntoScope` option.
### The evaluate options (`EvaluateOptions`)
All options are optional.
```typescript
type EvaluateOptions<TScope> = {
mdxOptions?: EvaluateMdxOptions;
disableExports?: boolean;
disableImports?: boolean;
parseFrontmatter?: boolean;
scope?: TScope;
vfileDataIntoScope?: VfileDataIntoScope;
};
```
#### `mdxOptions`
It is an **`EvaluateMdxOptions`** option to be passed to **`@mdx-js/mdx`** compiler.
```typescript
import { type EvaluateOptions as OriginalEvaluateOptions } from "@mdx-js/mdx";
type EvaluateMdxOptions = Omit<
OriginalEvaluateOptions,
| "Fragment"
| "jsx"
| "jsxs"
| "jsxDEV"
| "useMDXComponents"
| "providerImportSource"
| "outputFormat"
>;
```
As you see, some of the options are omitted and opinionated within the package. For example the `outputFormat` is always `function-body` by default. Visit https://mdxjs.com/packages/mdx/#evaluateoptions for available mdxOptions.
```typescript
const options: EvaluateOptions = {
// ...
mdxOptions: {
format: "mdx",
baseUrl: import.meta.url,
development: true,
remarkPlugins: [/* */],
rehypePlugins: [/* */],
recmaPlugins: [/* */],
remarkRehypeOptions: {handlers: {/* */}},
// ...
};
};
```
For more information see [the MDX documentation](https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js).
#### `disableExports`
It is a **boolean** option whether or not stripping the `export statements` out from the MDX source.
By default it is **false**, meaningly the `export statements` work as expected.
```typescript
const options: EvaluateOptions = {
disableExports: true;
};
```
Now, the `export statements` will be stripped out from the MDX.
#### `disableImports`
It is a **boolean** option whether or not stripping the `import statements` out from the MDX source.
By default it is **false**, meaningly the `import statements` work as expected.
```typescript
const options: EvaluateOptions = {
disableImports: true;
};
```
Now, the `import statements` will be stripped out from the MDX.
#### `parseFrontmatter`
It is a **boolean** option whether or not the frontmatter should be parsed out of the MDX.
By default it is **false**, meaningly the `frontmatter` will not be parsed and extracted.
```typescript
const options: EvaluateOptions = {
parseFrontmatter: true;
};
```
Now, the `frontmatter` part of the MDX file is parsed and extracted from the MDX source; and will be supplied into the MDX file so as you to use it within the javascript statements.
> [!NOTE]
> Frontmatter is a way to identify metadata in Markdown files. Metadata can literally be anything you want it to be, but often it's used for data elements your page needs and you don't want to show directly.
```mdx
---
title: "My Article"
author: "ipikuka"
---
# {frontmatter.title}
It is written by {frontmatter.author}
```
The package uses the `vfile-matter` internally to parse the frontmatter.
#### `scope`
It is an **`Record<string, unknown>`** option which is an arbitrary object of data which will be supplied to the MDX. For example, in cases where you want to provide template variables to the MDX, like `my name is {name}`, you could provide scope as `{ name: "ipikuka" }`.
Here is another example:
```typescript
const options: EvaluateOptions = {
scope: {
readingTime: calculateSomeHow(source)
};
};
```
Now, the `scope` will be supplied into the MDX file so as you to use it within the statements.
```markdown
# My article
read in {readingTime} min.
```
The variables within the expression in the MDX content should be valid javascript variable names. **Therefore, each key of the scope must be a valid variable name.**
```markdown
My name is {name} valid expression.
My name is {my-name} is not valid expression, which will throw error
```
So, we can say for the `scope`, here:
```typescript
const options: EvaluateOptions = {
scope: {
name: "ipikuka", // valid usage
"my-name": "ipikuka", // is not valid and error prone for the MDX content !!!
};
};
```
> [!TIP]
> The scope variables can be consumed not only as a property of a component, but also within the texts.
```mdx
my name is {name}
<BarComponent name={name} />
```
#### `vfileDataIntoScope`
It is an **union** type option. It is for passing some fields of `vfile.data` into the `scope` by mutating the `scope`.
> [!IMPORTANT]
> It provides referencial copy for objects and arrays. If the `scope` has the same key already, `vfile.data` overrides it.
The reason behind of this option is that `vfile.data` may hold some extra information added by some remark plugins. Some fields of the `vfile.data` may be needed to pass into the `scope` so as you to use in the MDX.
```typescript
type VfileDataIntoScope =
| true // all fields from vfile.data
| string // one specific field
| { name: string; as: string } // one specific field but change the key as
| Array<string | { name: string; as: string }>; // more than one field
```
```typescript
const options: EvaluateOptions = {
// Let's assume you use "remark-flexible-toc" plugin which composes
// the table of content (TOC) within the 'vfile.data.toc'
vfileDataIntoScope: "toc"; // or fileDataIntoScope: ["toc"];
};
```
Now, `vfile.data.toc` is copied into the scope as `scope["toc"]`, and will be supplied to the MDX via `scope`.
```mdx
# My article
<TableOfContentComponent toc={toc} />
```
If you need to change the name of the field, specify it for example `{ name: "toc", as: "headings" }`.
```typescript
const options: EvaluateOptions = {
vfileDataIntoScope: { name: "toc", as: "headings" };
};
```
```mdx
# My article
<TableOfContentComponent headings={headings} />
```
If you need to pass all the fields from `vfile.data`, specify it as `true`
```typescript
const options: EvaluateOptions = {
vfileDataIntoScope: true;
};
```
### The `MDXRemote` component
_Go to the [evaluate](#the-evaluate-function) function_
The `MDXRemote` component is used for rendering the MDX content on the server side. It is a react server component.
```typescript
async function MDXRemote(props: MDXRemoteProps): Promise<React.JSX.Element> {}
```
The `MDXRemote` component takes `MDXRemoteProps` and returns `React.JSX.Element` as a promise.
**Props of the `MDXRemote` component**
```typescript
type MDXRemoteProps<TScope> = {
source: Compatible;
options?: MDXRemoteOptions<TScope>;
components?: MDXComponents;
onError?: React.ComponentType<{ error: Error }>
};
```
The `MDXRemote` has **internal error handling mechanism** as much as it can, in order to do so, it takes **`onError`** prop in addition to `evaluate` function.
> [!CAUTION]
> The eval of the compiled source returns a module `MDXModule`, and does not throw errors except syntax errors. Some errors throw during the render process which needs you to use an **ErrorBoundary**.
```tsx
import { Suspense } from "react";
import { MDXRemote, type MDXRemoteOptions } from "next-mdx-remote-client/rsc";
import { ErrorComponent, LoadingComponent } from "../components";
import { components } from "../mdxComponents";
export default async function MDXComponent({ source }: {source?: string}) {
if (!source) {
return <ErrorComponent error="The source could not found !" />;
}
const options: MDXRemoteOptions = {
/* */
};
return (
<Suspense fallback={<LoadingComponent />}>
<MDXRemote
source={source}
options={options}
components={components}
onError={ErrorComponent}
/>
</Suspense>
);
};
```
### The MDXRemote options (`MDXRemoteOptions`)
All options are optional.
```typescript
type MDXRemoteOptions<TScope> = {
mdxOptions?: EvaluateMdxOptions;
disableExports?: boolean;
disableImports?: boolean;
parseFrontmatter?: boolean;
scope?: TScope;
vfileDataIntoScope?: VfileDataIntoScope;
};
```
The details are the same with the [EvaluateOptions](#the-evaluate-options-evaluateoptions).
## The part associated with Next.js `pages` router
_Go to [the part associated with Next.js app router](#the-part-associated-with-nextjs-app-router)_
**`next-mdx-remote-client`** exposes **`serialize`**, **`hydrate`** functions and **`MDXClient`** component for **"pages" router**.
The `serialize` function is used on the server side in "pages" router, while as the `hydrate` and the `MDXClient` are used on the client side in "pages" router. That is why the "serialize" function is purposefully isolated considering it is intended to run on the server side.
Let's give some examples how to use **`next-mdx-remote-client`** in "pages" router first, then explain the exposed functions and component.
### Examples for `pages` router
See a **demo application** with **`pages` router**, visit [source code](https://github.com/talatkuyuk/next-mdx-remote-client-in-pages-router) or [living web site](https://nmrc-in-pages-router.vercel.app/).
#### An example with `javascript`
```jsx
import { serialize } from 'next-mdx-remote-client/serialize';
import { MDXClient } from 'next-mdx-remote-client';
import ErrorComponent from '../components/ErrorComponent';
import Test from '../mdxComponents/Test';
const components = {
Test,
wrapper: ({children}) => <div className="mdx-wrapper">{children}</div>,
}
export default function Page({ mdxSource }) {
if ("error" in mdxSource) {
return <ErrorComponent error={mdxSource.error} />;
}
return <MDXClient {...mdxSource} components={components} />;
}
export async function getStaticProps() {
const source = "Some **bold text** in MDX, with a component <Test />";
const mdxSource = await serialize({source});
return { props: { mdxSource } };
}
```
#### An example with `typescript`, parsing frontmatter and providing custom data with scope
```tsx
import { MDXClient, type MDXComponents } from 'next-mdx-remote-client';
import { serialize } from "next-mdx-remote-client/serialize";
import type { SerializeOptions, SerializeResult } from "next-mdx-remote-client/serialize";
import { calculateSomeHow, getSourceSomeHow } from "../utils";
import ErrorComponent from '../components/ErrorComponent';
import Test from '../mdxComponents/Test';
type Scope = {
readingTime: string;
};
type Frontmatter = {
title: string;
author: string;
};
const components: MDXComponents = {
Test,
wrapper: function ({ children }: React.ComponentPropsWithoutRef<"div">) {
return <div className="mdx-wrapper">{children}</div>;
},
}
type Props = {
mdxSource?: SerializeResult<Frontmatter, Scope>;
}
export default function Page({ mdxSource }: Props) {
if (!mdxSource) {
return <ErrorComponent error="The source could not found !" />;
}
if ("error" in mdxSource) {
return <ErrorComponent error={mdxSource.error} />;
}
return (
<>
<h1>{mdxSource.frontmatter.title}</h1>
<p>Written by {mdxSource.frontmatter.author}; read in {mdxSource.scope.readingTime}</p>
<MDXClient {...mdxSource} components={components} />
</>
);
}
export async function getStaticProps() {
const source = await getSourceSomeHow();
if (!source) return { props: {} };
const options: SerializeOptions<Scope> = {
disableImports: true,
mdxOptions: {
// ...
},
parseFrontmatter: true,
scope: {
readingTime: calculateSomeHow(source),
},
};
const mdxSource = await serialize<Frontmatter, Scope>({source, options});
return { props: { mdxSource } };
}
```
#### An example with creating a table of contents (TOC)
I assume you have a MDX content having `<TableOfContentComponent />` inside; and you've provided it in MDX components.
```markdown
---
title: My Article
---
# {frontmatter.title}
<TableOfContentComponent toc={toc} />
rest of the article...
```
You can have a look at an example [TableOfContentComponent](https://github.com/talatkuyuk/next-mdx-remote-client-in-pages-router/blob/main/mdxComponents/Toc.tsx) in the demo application.
In order to create a table of contents (TOC) I use **`remark-flexible-toc`** in the remark plugins and pass the table of contents objects `vFile.data.toc` into the `scope` via the option `vfileDataIntoScope`.
That's it! So easy!
```tsx
import { MDXClient, type MDXComponents } from 'next-mdx-remote-client';
import { serialize } from "next-mdx-remote-client/serialize";
import type { SerializeOptions, SerializeResult } from "next-mdx-remote-client/serialize";
import remarkFlexibleToc, {type TocItem} from "remark-flexible-toc"; // <---------
import { calculateSomeHow, getSourceSomeHow } from "../utils";
import { ErrorComponent, TableOfContentComponent } from '../components';
import { Test } from '../mdxComponents';
type Scope = {
readingTime: string;
};
type Frontmatter = {
title: string;
author: string;
};
const components: MDXComponents = {
Test,
wrapper: function ({ children }: React.ComponentPropsWithoutRef<"div">) {
return <div className="mdx-wrapper">{children}</div>;
},
}
type Props = {
mdxSource?: SerializeResult<Frontmatter, Scope & {toc: TocItem[]}>;
}
export default function Page({ mdxSource }: Props) {
if (!mdxSource) {
return <ErrorComponent error="The source could not found !" />;
}
if ("error" in mdxSource) {
return <ErrorComponent error={mdxSource.error} />;
}
return (
<>
<h1>{mdxSource.frontmatter.title}</h1>
<p>Written by {mdxSource.frontmatter.author}; read in {mdxSource.scope.readingTime}</p>
<TableOfContentComponent toc={mdxSource.scope.toc /* <----- here added TOC */} />
<MDXClient {...mdxSource} components={components} />
</>
);
}
export async function getStaticProps() {
const source = await getSourceSomeHow();
if (!source) return { props: {} };
const options: SerializeOptions<Scope> = {
disableImports: true,
mdxOptions: {
remarkPlugins: [
// ...
remarkFlexibleToc, // <---------
],
},
parseFrontmatter: true,
scope: {
readingTime: calculateSomeHow(source),
},
vfileDataIntoScope: "toc", // <---------
};
const mdxSource = await serialize<Frontmatter, Scope>({source, options});
return { props: { mdxSource } };
}
```
Actually, you may not need to access the "frontmatter" and "scope" in JSX, you can use them within MDX directly, and return just `<MDXClient />` only.
```tsx
// ...
const components: MDXComponents = {
TableOfContentComponent, // <---------
wrapper: function ({ children }: React.ComponentPropsWithoutRef<"div">) {
return <div className="mdx-wrapper">{children}</div>;
},
}
// ...
export default function Page({ mdxSource }: Props) {
// ...
return (
<MDXClient {...mdxSource} components={components} />
);
}
```
_article.mdx_
```markdown
# {frontmatter.title}
Written by {frontmatter.author}; read in {readingTime}
<TableOfContentComponent toc={toc} />
rest of the article...
```
After the examples given, let's dive into the exposed functions and component by **`next-mdx-remote-client`** for "pages" router.
### The `serialize` function
_Go to the [hydrate](#the-hydrate-function) function_
_or the [MDXClient](#the-mdxclient-component) component_
```typescript
import { serialize } from "next-mdx-remote-client/serialize";
```
The `serialize` function is used for **compiling** MDX source, in other words **constructing compiled source** from MDX source, intended to run on server side at build time.
> [!WARNING]
> The `serialize` function is **asyncronous** and to be used within the `getStaticProps` or the `getServerSideProps` on the server side. (Off the record, it can be used within an `useEffect` as well, but this is not recommended because it is a heavy function as having more dependencies).
```typescript
async function serialize(props: SerializeProps): Promise<SerializeResult> {}
```
The `serialize` function takes `SerializeProps` and returns `SerializeResult` as a promise.
**Props of the `serialize` function**
```typescript
type SerializeProps<TScope> = {
source: Compatible;
options?: SerializeOptions<TScope>;
};
```
**Result of the `serialize` function**
Either the `compiledSource` or the `error` exists, in addition to `frontmatter` and `scope`.
```typescript
type SerializeResult<TFrontmatter, TScope> =
({ compiledSource: string } | { error: Error })
& {
frontmatter: TFrontmatter;
scope: TScope;
};
```
The `serialize` function has **internal error handling mechanism** for the MDX syntax errors. The catched error is serialized via **`serialize-error`** and attached into the serialize results, further you can deserialize the error on the client, if necessary. **You don't need to implement error handling by yourself.**
```tsx
import { serialize, type SerializeOptions } from "next-mdx-remote-client/serialize";
import type { Frontmatter, Scope } from "./types"
export async function getStaticProps() {
const source = await getSourceSomeHow();
if (!source) {
return { props: {} };
}
const options: SerializeOptions = {
/* */
};
const mdxSource = await serialize<Frontmatter, Scope>({
source,
options,
});
return {
props: {
mdxSource,
},
};
}
```
If you provide **the generic type parameters** like `await serialize<Frontmatter, Scope>(){}`, the `frontmatter` and the `scope` get the types, otherwise `Record<string, unknown>` by default for both.
> [!WARNING]
> Pay attention to the order of the generic type parameters.\
> \
> The type parameters `Frontmatter` and `Scope` should extend `Record<string, unknown>`. You should use **`type`** instead of **`interface`** for type parameters otherwise, you will receive an error saying `Type 'Xxxx' does not satisfy the constraint 'Record<string, unknown>'.` See this [issue](https://github.com/ipikuka/next-mdx-remote-client/issues/2) for more explanation.
The `nextjs` will send the `mdxSource` ((**`compiledSource`** or **`error`**) + **`frontmatter`** + **`scope`**) to client side.
**On client side, you need first to narrow the `mdxSource` by checking `if ("error" in mdxSource) {}`.**
```tsx
type Props = {
mdxSource?: SerializeResult<Frontmatter, Scope>;
}
export default function Page({ mdxSource }: Props) {
// ...
if ("error" in mdxSource) {
return <ErrorComponent error={mdxSource.error} />;
}
// ...
};
```
### The serialize options (`SerializeOptions`)
All options are optional.
```typescript
type SerializeOptions<TScope> = {
mdxOptions?: SerializeMdxOptions;
disableExports?: boolean;
disableImports?: boolean;
parseFrontmatter?: boolean;
scope?: TScope;
vfileDataIntoScope?: VfileDataIntoScope;
};
```
Except the `mdxOptions`, the details are the same with the [EvaluateOptions](#the-evaluate-options-evaluateoptions).
#### `mdxOptions`
It is a **`SerializeMdxOptions`** option to be passed to **`@mdx-js/mdx`** compiler.
```typescript
import { type CompileOptions as OriginalCompileOptions } from "@mdx-js/mdx";
type SerializeMdxOptions = Omit<
OriginalCompileOptions,
"outputFormat" | "providerImportSource"
>;
```
As you see, some of the options are omitted and opinionated within the package. For example the `outputFormat` is always `function-body` by default. Visit https://mdxjs.com/packages/mdx/#compileoptions for available mdxOptions.
```typescript
const options: SerializeOptions = {
// ...
mdxOptions: {
format: "mdx",
baseUrl: import.meta.url,
development: true,
remarkPlugins: [/* */],
rehypePlugins: [/* */],
recmaPlugins: [/* */],
remarkRehypeOptions: {handlers: {/* */}},
// ...
};
};
```
> [!WARNING]
> Here I need to mention about the `scope` option again for the `serialize`.\
> \
> **scope**\
> \
> Actually, the `serialize` doesn't do so much with the `scope` except you provide the option `vfileDataIntoScope` for passing data from `vfile.data` into the `scope`. Since the `scope` is passed from the server to the client by `nextjs`, the `scope` must be serializable. The `scope` can not hold **function**, **component** , **Date**, **undefined**, **Error object** etc.\
> \
> If the scope has to have **unserializable** information or if you don't need or don't want to pass the `scope` into the `serialize`, you can pass it into `hydrate` or `MDXClient` directly on the client side.
### The `hydrate` function
_Go to the [serialize](#the-serialize-function) function_
_or the [MDXClient](#the-mdxclient-component) component_
```typescript
import { hydrate } from "next-mdx-remote-client/csr";
```
The `hydrate` function is used for **constructing compiled source**, getting exported information from MDX and returning MDX content to be rendered on the client side.
```typescript
function hydrate(props: HydrateProps): HydrateResult {}
```
The `hydrate` function takes `HydrateProps` and returns `HydrateResult`. The `hydrate` has no "options" parameter.
**Props of the `hydrate` function**
```typescript
type HydrateProps = {
compiledSource: string;
frontmatter?: Record<string, unknown>;
scope?: Record<string, unknown>;
components?: MDXComponents;
disableParentContext?: boolean;
};
```
The option `disableParentContext` is a feature of **`@mdx-js/mdx`**. If it is `false`, the mdx components provided by parent `MDXProvider`s are going to be disregarded.
**Result of the `hydrate` function**
```typescript
type HydrateResult = {
content: React.JSX.Element;
mod: Record<string, unknown>;
error?: Error;
};
```
The **`mod`** object is for exported information from MDX source.
> [!TIP]
> If you need to get the **exports** from MDX --> use **`hydrate`**\
> If you don't need --> use **`MDXClient`**
The `hydrate` has **internal error handling mechanism** as much as it can, in order to do so, it returns an **`error`** object if it is catched.
> [!CAUTION]
> The eval of the compiled source returns a module `MDXModule`, and does not throw errors except syntax errors. Some errors throw during the render process which needs you to use an **ErrorBoundary**.
```tsx
import { hydrate, type SerializeResult } from "next-mdx-remote-client/csr";
import { ErrorComponent, TableOfContentComponent } from "../components";
import { components } from "../mdxComponents";
import type { Frontmatter, Scope } from "../types"
type Props = {
mdxSource?: SerializeResult<Frontmatter, Scope>;
}
export default function Page({ mdxSource }: Props) {
if (!mdxSource) {
return <ErrorComponent error="The source could not found !" />;
}
if ("error" in mdxSource) {
return <ErrorComponent error={mdxSource.error} />;
}
// Now, mdxSource has {compiledSource, frontmatter, scope}
const { content, mod, error } = hydrate({ ...mdxSource, components });
if (error) {
return <ErrorComponent error={error} />;
}
// You can use the "mod" object for exported information from the MDX as you wish
return (
<>
<h1>{mdxSource.frontmatter.title}</h1>
<div><em>{mod.something}</em></div>
<TableOfContentComponent toc={mdxSource.scope.toc} />
{content}
</>
);
};
```
In the above example, I assume you use **`remark-flexible-toc`** remark plugin in order to collect the headings from MDX content, and you pass that information into the `scope` via `vfileDataIntoScope` option within the serialize on the server side.
### The `MDXClient` component
_Go to the [serialize](#the-serialize-function) function_
_or the [hydrate](#the-hydrate-function) function_
```typescript
import { MDXClient } from "next-mdx-remote-client/csr";
```
The `MDXClient` component is used for rendering the MDX content on the client side.
```typescript
function MDXClient(props: MDXClientProps): React.JSX.Element {}
```
The `MDXClient` component takes `MDXClientProps` and returns `React.JSX.Element`. The `MDXClient` has no "options" parameter like `hydrate`.
**Props of the `MDXClient` component**
```typescript
type MDXClientProps = {
compiledSource: string;
frontmatter?: Record<string, unknown>;
scope?: Record<string, unknown>;
components?: MDXComponents;
disableParentContext?: boolean;
onError?: React.ComponentType<{ error: Error }>
};
```
The option `disableParentContext` is a feature of **`@mdx-js/mdx`**. If it is `false`, the mdx components provided by parent `MDXProvider`s are going to be disregarded.
> [!TIP]
> If you need to get the **exports** from MDX --> use **`hydrate`**\
> If you don't need --> use **`MDXClient`**
The `MDXClient` has **internal error handling mechanism** as much as it can, in order to do so, it takes **`onError`** prop in addition to `hydrate` function.
> [!CAUTION]
> The eval of the compiled source returns a module `MDXModule`, and does not throw errors except syntax errors. Some errors throw during the render process which needs you to use an **ErrorBoundary**.
```tsx
import { MDXClient, type SerializeResult } from "next-mdx-remote-client/csr";
import { ErrorComponent, TableOfContentComponent } from "../components";
import { components } from "../mdxComponents";
import type { Frontmatter, Scope } from "../types"
type Props = {
mdxSource?: SerializeResult<Frontmatter, Scope>;
}
export default function Page({ mdxSource }: Props) {
if (!mdxSource) {
return <ErrorComponent error="The source could not found !" />;
}
if ("error" in mdxSource) {
return <ErrorComponent error={mdxSource.error} />;
}
// Now, mdxSource has {compiledSource, frontmatter, scope}
return (
<>
<h1>{mdxSource.frontmatter.title}</h1>
<TableOfContentComponent toc={mdxSource.scope.toc} />
<MDXClient
{...mdxSource}
components={components}
onError={ErrorComponent}
/>
</>
);
};
```
In the above example, I assume you use **`remark-flexible-toc`** remark plugin in order to collect the headings from MDX content, and you pass that information into the `scope` via `vfileDataIntoScope` option within the serialize on the server side.
### The `hydrateLazy` function and the `MDXClientLazy` component
**`next-mdx-remote-client`** exports additional versions, say, the `hydrateLazy` and the `MDXClientLazy`, which both **have the same _functionality_, _props_, _results_** with the `hydrate` and the `MDXClient`, correspondently.
**The only difference is the hydration process takes place lazily** on the browser within a `window.requestIdleCallback` in a useEffect. You can use `hydrateLazy` or `MDXClientLazy` in order to defer hydration of the content and immediately serve the static markup.
```typescript
import { hydrateLazy, MDXClientLazy } from "next-mdx-remote-client/csr";
```
When you use `hydrateLazy`, and want to get the exports from MDX via `mod` object, please be aware that the `mod` object is always empty `{}` at first render, then it will get actual exports at second render.
> [!NOTE]
> Lazy hydration defers hydration of the components on the client. This is an optimization technique to improve the initial load of the application, but may introduce unexpected delays in interactivity for any dynamic content within the MDX content.\
> \
> This will add an additional wrapping div around the rendered MDX, which is necessary to avoid hydration mismatches during render.\
> \
> _For further explanation about the lazy hydration see [`next-mdx-remote`](https://github.com/hashicorp/next-mdx-remote) notes._
### The `hydrateAsync` function and the `MDXClientAsync` component
**`next-mdx-remote-client`** exports additional versions, say, the `hydrateAsync` and the `MDXClientAsync`.
These have additional props and options, but here, I don't want to give the details since **I created them for experimental** to show the `import statements` on the client side don't work. You can have a look at the github repository for the code and the tests.
**The main difference is that the eval of the compiled source takes place in a useEffect** on the browser, since the compile source has `await` keyword for `import statements`.
```typescript
import { hydrateAsync, MDXClientAsync } from "next-mdx-remote-client/csr";
```
> [!NOTE]
> I believe, it is viable somehow using `dynamic` API if the `vercel` supports for a solution for the `pages` router via `import.meta` APIs. During the compilation of the MDX in the `serialize`, a remark/recma plugin can register the imported modules into the `import.meta.url` via a nextjs API (needs support of vercel) for them will be available to download/import on the client side via `dynamic` api. This is my imagination.
### The `MDXProvider` component
The package exports the `MDXProvider` from **`@mdx-js/react`**, in order the developers don't need to install **`@mdx-js/react`**.
```typescript
import { MDXProvider } from "next-mdx-remote-client/csr";
```
The `<MDXProvider />` makes the mdx components available to any `<MDXClient />` or `hydrate's { content }` being rendered in the application, as a child status of that provider.
For example, you can wrap the whole application so as **you do not need to supply the mdx components into any `<MDXClient />` or `hydrate's { content }`.**
```tsx
import { MDXProvider } from 'next-mdx-remote-client';
import { components } from "../mdxComponents";
export default function App({ Component, pageProps }) {
return (
<MDXProvider components={components}>
<Component {...pageProps} />
</MDXProvider>
)
}
```
> [!NOTE]
> How this happens, because **`next-mdx-remote-client`** injects the `useMdxComponents` context hook from **`@mdx-js/react`** during the function construction of the compiled source, internally. Pay attention that it is valid for only `MDXClient` and `hydrate` functions.
> [!CAUTION]
> Since `MDXRemote` as a react server component can not read the context, **`MDXProvider` is effectless when used within the nextjs `app` router** for `MDXRemote`, which is also for `evaluate`.
## MDX Components
You can provide a map of custom MDX components, which is a feature of **`@mdx-js/mdx`**, in order to replace HTML tags (see [the list of markdown syntax and equivalent HTML tags](https://mdxjs.com/table-of-components)) with the custom components.
Typescript users can use `MDXComponents` from `mdx/types`, which is exported by this package as well.
`../mdxComponents/index.ts`
```tsx
import { type MDXComponents } from "next-mdx-remote-client";
import dynamic from "next/dynamic";
import Image from "next/image";
import Link from "next/link";
import { Typography } from "@material-ui/core";
import { motion } from 'framer-motion'
import Hello from "./Hello";
import CountButton from "./CountButton";
import BlockQuote, { default as blockquote } from "./BlockQuote";
import pre from "./pre";
export const mdxComponents: MDXComponents = {
Hello,
CountButton,
Dynamic: dynamic(() => import("./dynamic")),
Image,
Link,
motion: { div: () => <div>Hello world</div> },
h2: (props: React.ComponentPropsWithoutRef<"h2">) => (
<Typography variant="h2" {...props} />
),
strong: (props: React.ComponentPropsWithoutRef<"strong">) => (
<strong className="custom-strong" {...props} />
),
em: (props: React.ComponentPropsWithoutRef<"em">) => (
<em className="custom-em" {...props} />
),
pre,
blockquote,
BlockQuote,
wrapper: (props: { children: any }) => {
return <div id="mdx-layout">{props.children}</div>;
}
};
```
> [!NOTE]
> The **`wrapper`** is a special key, if you want to wrap the MDX content with a HTML container element.
`./data/my-article.mdx`
```markdown
---
title: "My Article"
author: "ipikuka"
---
_Read in {readingTime}, written by <Link href="#">**{frontmatter.author}**</Link>_
# {frontmatter.title}
## Sub heading for custom components
<Hello name={foo} />
<CountButton />
<Dynamic />
<Image src="/images/cover.png" alt="cover" width={180} height={40} />
<BlockQuote>
I am blackquote content
</BlockQuote>
<motion.div animate={{ x: 100 }} />
## Sub heading for some markdown elements

Here is _italic text_ and **strong text**
> I am blackquote content
```
## Utility `getFrontmatter`
The package exports one utility **`getFrontmatter`** which is **for getting frontmatter without compiling the source**. You can get the fronmatter and the stripped source by using the `getFrontmatter` which employs the same frontmatter extractor **`vfile-matter`** used within the package.
```typescript
import { getFrontmatter } from "next-mdx-remote-client/utils";
const { frontmatter, strippedSource } = getFrontmatter<TFrontmatter>(source);
```
If you provide **the generic type parameter**, it ensures the `frontmatter` gets the type, otherwise `Record<string, unknown>` by default.
**If there is no frontmatter** in the source, the `frontmatter` will be **empty object `{}`**.
> [!IMPORTANT]
> \
> If you use **`next-mdx-remote`** and want to get `frontmatter` without compiling the source !
> \
> The subpath **`next-mdx-remote-client/utils`** is isolated from other features of the package and it does cost minimum. **So, anyone can use `next-mdx-remote-client/utils` while using `next-mdx-remote`.**
## Types
**`next-mdx-remote-client`** is fully typed with [TypeScript][url-typescript].
The package exports the types for server side (rsc):
- `EvaluateProps`
- `EvaluateOptions`
- `EvaluateResult`
- `MDXRemoteProps`
- `MDXRemoteOptions`
The package exports the types for client side (csr):
- `HydrateProps`
- `HydrateResult`
- `MDXClientProps`
- `SerializeResult`
The package exports the types for the serialize function:
- `SerializeProps`
- `SerializeOptions`
- `SerializeResult`
In addition, the package exports the types from `mdx/types` so that developers do not need to import `mdx/types`:
- `MDXComponents`
- `MDXContent`
- `MDXProps`
- `MDXModule`
## Compatibility
**`next-mdx-remote-client`** works with unified version 6+ ecosystem since it is compatible with MDX version 3.
## Security
The security model of **`next-mdx-remote-client`** is fundamentally the same as other MDX integrations built on top of **`@mdx-js/mdx`**, including **`next-mdx-remote`**, **`@next/mdx`**, and similar solutions.
MDX supports **JSX syntax**; **JavaScript expressions** (`{1 + 1}`, `{someVar}`, `{fn()}`); and **ESM blocks (`mdxjsEsm`)** such as `import` and `export`.
Because MDX compiles to executable JavaScript, rendering **untrusted MDX** can inherently introduce **Cross-Site Scripting (XSS)** and **Remote Code Execution (RCE)**.
This is not unique to **`next-mdx-remote-client`**; it is intrinsic to how MDX works and has long been documented across the MDX ecosystem.
### Trust Model
If MDX content is **not fully trusted**, then **RCE** is inherently possible. If you completely block all JavaScript expressions, you effectively reduce MDX to *Markdown with JSX*. That may be acceptable for certain use cases, but it changes the expressive nature of MDX.
A more balanced approach is to **block only dangerous expressions** rather than disabling all expressions. The remark plugin [**`remark-mdx-remove-expressions`**](https://github.com/ipikuka/remark-mdx-remove-expressions) can remove executable or dangerous MDX expressions at the syntax level:
```ts
import remarkMdxRemoveExpressions from "remark-mdx-remove-expressions";
{
mdxOptions: {
remarkPlugins: [
[remarkMdxRemoveExpressions, { onlyDangerousExpressions: true }]
]
}
}
```
### ESM (`import` / `export`) in MDX
Allowing **`import` declarations** and **`export` declarations** inside MDX can introduce serious risks if the content is not strictly controlled. **`next-mdx-remote-client`** provides options to disable ESM blocks (`mdxjsEsm`) for this reason.
But *dynamic import expressions*, such as `await import("some-module")` are JavaScript expressions and require a **custom recma plugin** to block or transform them. [**`remark-mdx-remove-expressions`**](https://github.com/ipikuka/remark-mdx-remove-expressions) can also remove import expressions, **`next-mdx-remote-client`** does not modify or restrict these automatically.
### Runtime Evaluation (`eval` / `new Function`)
Like most MDX runtimes, **`next-mdx-remote-client`** evaluates compiled JavaScript using runtime evaluation `Reflect.construct` similar with `eval` or `new Function()`.
Evaluating JavaScript from a string can enable **XSS** attacks or **RCE** if the input is not trusted. You are responsible for ensuring either the MDX source is trusted, or the source is properly sanitized and restricted before evaluation. Please, take your own measures while passing the user input.
### Content Security Policy (CSP)
If your site uses a strict **Content Security Policy (CSP)** that disallows dynamic code evaluation via `eval` or `new Function()`, you will need to loosen the `script-src` policy to include `unsafe-eval`. Otherwise, MDX runtime evaluation will fail.
Carefully assess the security implications before enabling [`unsafe-eval`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#common_sources), especially in high-security environments.
### Final Security Recommendations
- Treat MDX as executable code.
- Never evaluate/render untrusted MDX without applying proper restrictions or sanitization.
- Prefer removing dangerous expressions at the **remark/recma stage**, not at the rendering layer.
- Disable ESM blocks if the content is not fully controlled.
- Understand your CSP implications before deploying to production.
## Some Plugins
I like to contribute the Unified / Remark / MDX ecosystem, so I recommend you to have a look my plugins.
### My Remark Plugins
- [`remark-flexible-code-titles`](https://www.npmjs.com/package/remark-flexible-code-titles)
– Remark plugin to add titles or/and containers for the code blocks with customizable properties
- [`remark-flexible-containers`](https://www.npmjs.com/package/remark-flexible-containers)
– Remark plugin to add custom containers with customizable properties in markdown
- [`remark-ins`](https://www.npmjs.com/package/remark-ins)
– Remark plugin to add `ins` element in markdown
- [`remark-flexible-paragraphs`](https://www.npmjs.com/package/remark-flexible-paragraphs)
– Remark plugin to add custom paragraphs with customizable properties in markdown
- [`remark-flexible-markers`](https://www.npmjs.com/package/remark-flexible-markers)
– Remark plugin to add custom `mark` element with customizable properties in markdown
- [`remark-flexible-toc`](https://www.npmjs.com/package/remark-flexible-toc)
– Remark plugin to expose the table of contents via Vfile.data or via an option reference
- [`remark-mdx-remove-esm`](https://www.npmjs.com/package/remark-mdx-remove-esm)
– Remark plugin to remove import and/or export statements (mdxjsEsm)
- [`remark-mdx-remove-expressions`](https://www.npmjs.com/package/remark-mdx-remove-expressions)
– Remark plugin to remove MDX expressions within curlybraces {} in MDX content
### My Rehype Plugins
- [`rehype-pre-language`](https://www.npmjs.com/package/rehype-pre-language)
– Rehype plugin to add language information as a property to `pre` element
- [`rehype-highlight-code-lines`](https://www.npmjs.com/package/rehype-highlight-code-lines)
– Rehype plugin to add line numbers to code blocks and allow highlighting of desired code lines
- [`rehype-code-meta`](https://www.npmjs.com/package/rehype-code-meta)
– Rehype plugin to copy `code.data.meta` to `code.properties.metastring`
- [`rehype-image-toolkit`](https://www.npmjs.com/package/rehype-image-toolkit)
– Rehype plugin to enhance Markdown image syntax `![]()` and Markdown/MDX media elements (`<img>`, `<audio>`, `<video>`) by auto-linking bracketed or parenthesized image URLs, wrapping them in `<figure>` with optional captions, unwrapping images/videos/audio from paragraph, parsing directives in title for styling and adding attributes, and dynamically converting images into `<video>` or `<audio>` elements based on file extension.
### My Recma Plugins
- [`recma-mdx-escape-missing-components`](https://www.npmjs.com/package/recma-mdx-escape-missing-components)
– Recma plugin to set the default value `() => null` for the Components in MDX in case of missing or not provided so as not to throw an error
- [`recma-mdx-change-props`](https://www.npmjs.com/package/recma-mdx-change-props)
– Recma plugin to change the `props` parameter into the `_props` in the `function _createMdxContent(props) {/* */}` in the compiled source in order to be able to use `{props.foo}` like expressions. It is useful for the `next-mdx-remote` or `next-mdx-remote-client` users in `nextjs` applications.
- [`recma-mdx-change-imports`](https://www.npmjs.com/package/recma-mdx-change-imports)
– Recma plugin to convert import declarations for assets and media with relative links into variable declarations with string URLs, enabling direct asset URL resolution in compiled MDX.
- [`recma-mdx-import-media`](https://www.npmjs.com/package/recma-mdx-import-media)
– Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX.
- [`recma-mdx-import-react`](https://www.npmjs.com/package/recma-mdx-import-react)
– Recma plugin to ensure getting `React` instance from the arguments and to make the runtime props `{React, jsx, jsxs, jsxDev, Fragment}` is available in the dynamically imported components in the compiled source of MDX.
- [`recma-mdx-html-override`](https://www.npmjs.com/package/recma-mdx-html-override)
– Recma plugin to allow selected raw HTML elements to be overridden via MDX components.
- [`recma-mdx-interpolate`](https://www.npmjs.com/package/recma-mdx-interpolate)
– Recma plugin to enable interpolation of identifiers wrapped in curly braces within the `alt`, `src`, `href`, and `title` attributes of markdown link and image syntax in MDX.
### My Unist Utils and Unified Plugins
I also build low-level utilities and plugins for the Unified ecosystem that can be used across Remark, Rehype, Recma, and other unist-based abstract syntax trees (ASTs).
- [`unist-util-find-between`](https://www.npmjs.com/package/unist-util-find-between)
– Unist utility to find the nodes between two nodes.
- [`unified-log-tree`](https://www.npmjs.com/package/unified-log-tree)
– Unified plugin to log abstract syntax trees (ASTs) for debugging without mutating.
## License
[MPL 2.0 License](./LICENSE) © ipikuka
[MDX]: https://mdxjs.com/
[mdx-js-mdx]: https://github.com/mdx-js/mdx
[next-mdx-remote]: https://github.com/hashicorp/next-mdx-remote
[badge-npm-version]: https://img.shields.io/npm/v/next-mdx-remote-client
[badge-npm-download]:https://img.shields.io/npm/dt/next-mdx-remote-client
[url-npm-package]: https://www.npmjs.com/package/next-mdx-remote-client
[url-github-package]: https://github.com/ipikuka/next-mdx-remote-client
[badge-license]: https://img.shields.io/github/license/ipikuka/next-mdx-remote-client
[url-license]: https://github.com/ipikuka/next-mdx-remote-client/blob/main/LICENSE
[badge-publish-to-npm]: https://github.com/ipikuka/next-mdx-remote-client/actions/workflows/publish.yml/badge.svg
[url-publish-github-actions]: https://github.com/ipikuka/next-mdx-remote-client/actions/workflows/publish.yml
[badge-typescript]: https://img.shields.io/npm/types/next-mdx-remote-client
[url-typescript]: https://www.typescriptlang.org/
[badge-codecov]: https://codecov.io/gh/ipikuka/next-mdx-remote-client/graph/badge.svg?token=N0BPBCI5CC
[url-codecov]: https://codecov.io/gh/ipikuka/next-mdx-remote-client
[badge-type-coverage]: https://img.shields.io/badge/dynamic/json.svg?label=type-coverage&prefix=%E2%89%A5&suffix=%&query=$.typeCoverage.atLeast&uri=https%3A%2F%2Fraw.githubusercontent.com%2Fipikuka%2Fnext-mdx-remote-client%2Fmaster%2Fpackage.json
================================================
FILE: codecov.yml
================================================
coverage:
status:
project:
default:
target: 100%
================================================
FILE: eslint.config.js
================================================
import { defineConfig } from "eslint/config";
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import globals from "globals";
import react from "eslint-plugin-react";
import eslintPluginPrettier from "eslint-plugin-prettier";
import eslintConfigPrettier from "eslint-config-prettier";
export default defineConfig(
{
ignores: [
"**/archive/**",
"**/coverage/**",
"**/dist/**",
"**/node_modules/**",
"**/package-lock.json",
"**/.DS_Store",
"**/.vscode",
],
},
eslint.configs.recommended,
{
name: "TypeScript",
files: ["**/*.{ts,tsx}"],
extends: [eslint.configs.recommended, tseslint.configs.recommended],
plugins: {
react,
prettier: eslintPluginPrettier,
},
rules: {
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-explicit-any": "off",
},
},
{
name: "JavaScript",
files: ["**/*.{js,jsx}"],
extends: [tseslint.configs.disableTypeChecked],
},
{
name: "React",
files: ["**/*.jsx", "tests/context/ExampleForm.mjs"],
plugins: {
react,
prettier: eslintPluginPrettier,
},
languageOptions: {
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
globals: globals.browser,
},
},
{
name: "Idle Callback Polyfill",
files: ["src/csr/idle-callback-polyfill.js"],
languageOptions: {
sourceType: "script",
globals: globals.browser,
},
},
eslintConfigPrettier,
);
================================================
FILE: migration_guide.md
================================================
# Migration guide from `next-mdx-remote`
## Migration examples for "pages" router
All examples have been taken from **`next-mdx-remote`** to show exactly how to migrate the code.
<details>
<summary>Main example in the github page headline</summary>
```diff
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClient } from 'next-mdx-remote-client'
import { Test } from '../mdxComponents'
+ import { ErrorComponent } from '../components'
const components = { Test }
export default function TestPage({ source }) {
+ if ("error" in source) {
+ return <ErrorComponent error={source.error} />;
+ }
return (
<div className="wrapper">
- <MDXRemote {...source} components={components} />
+ <MDXClient {...source} components={components} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source = 'Some **mdx** text, with a component <Test />'
- const mdxSource = await serialize(source)
+ const mdxSource = await serialize({source})
return { props: { source: mdxSource } }
}
```
</details>
<details>
<summary>Parsing frontmatter</summary>
```diff
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClient } from 'next-mdx-remote-client'
import { Test } from '../mdxComponents'
+ import { ErrorComponent } from '../components'
const components = { Test }
export default function TestPage({ mdxSource }) {
+ if ("error" in mdxSource) {
+ return <ErrorComponent error={mdxSource.error} />;
+ }
return (
<div className="wrapper">
<h1>{mdxSource.frontmatter.title}</h1>
- <MDXRemote {...mdxSource} components={components} />
+ <MDXClient {...mdxSource} components={components} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source = `---
title: Test
---
Some **mdx** text, with a component <Test name={frontmatter.title}/>`
- const mdxSource = await serialize(source, { parseFrontmatter: true })
+ const mdxSource = await serialize({source, options: { parseFrontmatter: true }})
return { props: { mdxSource } }
}
```
</details>
<details>
<summary>Passing custom data to a component with `scope`</summary>
```diff
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClient } from 'next-mdx-remote-client'
import { Test } from '../mdxComponents'
+ import { ErrorComponent } from '../components'
const components = { Test }
const data = { product: 'next' }
export default function TestPage({ source }) {
+ if ("error" in source) {
+ return <ErrorComponent error={source.error} />;
+ }
return (
<div className="wrapper">
- <MDXRemote {...source} components={components} scope={data} />
+ <MDXClient {...source} components={components} scope={data} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source =
'Some **mdx** text, with a component using a scope variable <Test product={product} />'
- const mdxSource = await serialize(source)
+ const mdxSource = await serialize({source})
return { props: { source: mdxSource } }
}
```
</details>
<details>
<summary>Passing `scope` into the `serialize` function instead</summary>
```diff
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClient } from 'next-mdx-remote-client'
import { Test } from '../mdxComponents'
+ import { ErrorComponent } from '../components'
const components = { Test }
const data = { product: 'next' }
export default function TestPage({ source }) {
+ if ("error" in source) {
+ return <ErrorComponent error={source.error} />;
+ }
return (
<div className="wrapper">
- <MDXRemote {...source} components={components} />
+ <MDXClient {...source} components={components} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source =
'Some **mdx** text, with a component <Test product={product} />'
- const mdxSource = await serialize(source, { scope: data })
+ const mdxSource = await serialize({source, options: { scope: data }})
return { props: { source: mdxSource } }
}
```
</details>
<details>
<summary>
Custom components from <code>MDXProvider</code><a id="mdx-provider"></a>
</summary>
```diff
// pages/_app.jsx
- import { MDXProvider } from '@mdx-js/react'
+ import { MDXProvider } from 'next-mdx-remote-client'
import Test from '../mdxComponents/Test'
const components = { Test }
export default function MyApp({ Component, pageProps }) {
return (
<MDXProvider components={components}>
<Component {...pageProps} />
</MDXProvider>
)
}
```
```diff
// pages/test.jsx
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClient } from 'next-mdx-remote-client'
+ import { ErrorComponent } from '../components'
export default function TestPage({ source }) {
+ if ("error" in source) {
+ return <ErrorComponent error={source.error} />;
+ }
return (
<div className="wrapper">
- <MDXRemote {...source} />
+ <MDXClient {...source} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source = 'Some **mdx** text, with a component <Test />'
- const mdxSource = await serialize(source)
+ const mdxSource = await serialize({source})
return { props: { source: mdxSource } }
}
```
</details>
<details>
<summary>
Component names with dot (e.g. <code>motion.div</code>)
</summary>
```diff
import { motion } from 'framer-motion'
- import { MDXProvider } from '@mdx-js/react'
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClient, MDXProvider } from 'next-mdx-remote-client'
+ import { ErrorComponent } from '../components'
export default function TestPage({ source }) {
+ if ("error" in source) {
+ return <ErrorComponent error={source.error} />;
+ }
return (
<div className="wrapper">
- <MDXRemote {...source} components={{ motion }} />
+ <MDXClient {...source} components={{ motion }} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source = `Some **mdx** text, with a component:
<motion.div animate={{ x: 100 }} />`
- const mdxSource = await serialize(source)
+ const mdxSource = await serialize({source})
return { props: { source: mdxSource } }
}
```
</details>
<details>
<summary>Lazy hydration</summary>
```diff
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote } from 'next-mdx-remote'
+ import { serialize } from 'next-mdx-remote-client/serialize'
+ import { MDXClientLazy } from 'next-mdx-remote-client'
import { Test } from '../mdxComponents'
+ import { ErrorComponent } from '../components'
const components = { Test }
export default function TestPage({ source }) {
+ if ("error" in source) {
+ return <ErrorComponent error={source.error} />;
+ }
return (
<div className="wrapper">
- <MDXRemote {...source} components={components} lazy />
+ <MDXClientLazy {...source} components={components} />
</div>
)
}
export async function getStaticProps() {
// MDX text - can be from a local file, database, anywhere
const source = 'Some **mdx** text, with a component <Test />'
- const mdxSource = await serialize(source)
+ const mdxSource = await serialize({source})
return { props: { source: mdxSource } }
}
```
</details>
<details>
<summary>With typescript</summary>
```diff
import { type GetStaticProps } from 'next'
- import { serialize } from 'next-mdx-remote/serialize'
- import { MDXRemote, type MDXRemoteSerializeResult } from 'next-mdx-remote'
+ import { serialize, type SerializeResult } from 'next-mdx-remote-client/serialize'
+ import { MDXClient } from 'next-mdx-remote-client'
import { ExampleComponent } from './mdxComponents'
+ import { ErrorComponent } from '../components'
const components = { ExampleComponent }
- interface Props {
- mdxSource: MDXRemoteSerializeResult
- }
+ type Props = {
+ mdxSource: SerializeResult
+ }
export default function ExamplePage({ mdxSource }: Props) {
+ if ("error" in mdxSource) {
+ return <ErrorComponent error={mdxSource.error} />;
+ }
return (
<div>
+ <MDXRemote {...mdxSource} components={components} />
- <MDXClient {...mdxSource} components={components} />
</div>
)
}
export const getStaticProps: GetStaticProps<{
- mdxSource: MDXRemoteSerializeResult
+ mdxSource: SerializeResult
}> = async () => {
- const mdxSource = await serialize('some *mdx* content: <ExampleComponent />')
+ const mdxSource = await serialize({ source: 'some *mdx* content: <ExampleComponent />'})
return { props: { mdxSource } }
}
```
</details>
## Migration examples for "app" router
All examples have been taken from **`next-mdx-remote`** to show exactly how to migrate the code.
<details>
<summary>Basic example for React Server Components (RSC)</summary>
```diff
- import { MDXRemote } from 'next-mdx-remote/rsc'
+ import { MDXRemote } from 'next-mdx-remote-client/rsc'
+ import { ErrorComponent } from '../components'
// app/page.js
export default function Home() {
return (
<MDXRemote
source={`# Hello from Server Components`}
+ onEror={ErrorComponent}
/>
)
}
```
</details>
<details>
<summary>Loading state in "app" router</summary>
```diff
import { Suspense } from 'react'
- import { MDXRemote } from 'next-mdx-remote/rsc'
+ import { MDXRemote } from 'next-mdx-remote-client/rsc'
+ import { ErrorComponent } from '../components'
// app/page.js
export default function Home() {
return (
// In Next.js you can also use `loading.js` instead of <Suspense />
<Suspense fallback={<>Loading...</>}>
<MDXRemote
source={`# Hello from Server Components`}
+ onEror={ErrorComponent}
/>
</Suspense>
)
}
```
</details>
<details>
<summary>Custom components</summary>
```diff
// components/mdx-remote.js
- import { MDXRemote } from 'next-mdx-remote/rsc'
+ import { MDXRemote } from 'next-mdx-remote-client/rsc'
+ import { ErrorComponent } from '../components'
const components = {
h1: (props) => (
<h1 {...props} className="large-text">
{props.children}
</h1>
),
}
export function CustomMDX(props) {
return (
<MDXRemote
{...props}
components={{ ...components, ...(props.components || {}) }}
+ onEror={ErrorComponent}
/>
)
}
```
```diff
// app/page.js
import { CustomMDX } from '../components/mdx-remote'
export default function Home() {
return (
<CustomMDX
// h1 now renders with `large-text` className
source={`# Hello from Server Components`}
/>
)
}
```
</details>
<details>
<summary>Access `frontmatter` and `scope` outside of MDX</summary>
```diff
// app/page.js
- import { compileMDX } from 'next-mdx-remote/rsc'
+ import { evaluate } from 'next-mdx-remote-client/rsc'
+ import { ErrorComponent } from '../components'
export default async function Home() {
- const { content, frontmatter } = await compileMDX<{ title: string }>({
+ const { content, frontmatter, scope, error } = await evaluate<{ title: string }>({
source: `---
title: RSC Frontmatter Example
---
# Hello from {product}!`,
options: {
parseFrontmatter: true,
scope: {
product: 'Server Components'
},
},
})
+ if (error) {
+ return <ErrorComponent error={error} />;
+ }
return (
<>
<h1>{frontmatter.title}</h1>
+ <h2>{scope.product}</h2>
{content}
</>
)
}
```
</details>
## The differences between `next-mdx-remote` and `next-mdx-remote-client`
### `next-mdx-remote-client` has additional exported subpaths
**`🟥 next-mdx-remote`:**
```typescript
import /* */ from "next-mdx-remote";
import /* */ from "next-mdx-remote/serialize";
import /* */ from "next-mdx-remote/rsc";
```
**`🟩 next-mdx-remote-client`:**
```typescript
import /* */ from "next-mdx-remote-client";
import /* */ from "next-mdx-remote-client/serialize";
import /* */ from "next-mdx-remote-client/rsc";
// additional exported subpaths
import /* */ from "next-mdx-remote-client/csr";
import /* */ from "next-mdx-remote-client/utils";
```
> [!NOTE]
> The `next-mdx-remote-client` and the `next-mdx-remote-client/csr` refer to the same.
### Use `<MDXClient />` in the client side
**`🟥 next-mdx-remote`:**
It exports the components with the same name `<MDXRemote />` for both "app" and "pages" router.
```typescript
// for "pages" router, it is a client component
import { MDXRemote } from "next-mdx-remote";
// for "app" router, it is a server component
import { MDXRemote } from "next-mdx-remote/rsc";
```
**`🟩 next-mdx-remote-client`:**
It exports `<MDXClient />` for "pages" router, `<MDXRemote />` for "app" router.
```typescript
// for "pages" router, it is a client component
import { MDXClient } from "next-mdx-remote-client/csr";
// for "app" router, it is a server component
import { MDXRemote } from "next-mdx-remote-client/rsc";
```
## The part associated with Next.js `app` router
_Go to [the part associated with Next.js pages router](#the-part-associated-with-nextjs-pages-router)_
### The differences in module exports
**`🟥 next-mdx-remote`:**
```typescript
import { MDXRemote, compileMDX } from "next-mdx-remote/rsc";
```
**`🟩 next-mdx-remote-client`:**
```typescript
import { MDXRemote, evaluate } from "next-mdx-remote-client/rsc";
```
### The differences in type exports
**`🟥 next-mdx-remote`:**
```typescript
import type { MDXRemoteProps, CompileMDXResult, MDXRemoteSerializeResult } from "next-mdx-remote/rsc";
```
**`🟩 next-mdx-remote-client`:**
```typescript
import type { MDXRemoteProps, MDXRemoteOptions } from "next-mdx-remote-client/rsc";
import type { EvaluateProps, EvaluateOptions, EvaluateResult } from "next-mdx-remote-client/rsc";
```
### The differences in props
**`🟥 next-mdx-remote`:**
The `compileMDX` and `MDXRemote` take the same props `MDXRemoteProps`.
```typescript
type MDXRemoteProps = {
source: VFileCompatible
options?: SerializeOptions
components?: React.ComponentProps<typeof MDXProvider>['components']
}
```
**`🟩 next-mdx-remote-client`:**
The `evaluate` takes `EvaluateProps` which has a type argument, and **the same prop keys but different types**.
```typescript
type EvaluateProps<TScope> = {
source: Compatible;
options?: EvaluateOptions<TScope>;
components?: MDXComponents;
}
```
The `MDXRemote` takes `MDXRemoteProps` which has `onError` prop in addition to `EvaluateProps`.
```typescript
type MDXRemoteProps<TScope> = {
source: Compatible;
options?: EvaluateOptions<TScope>;
components?: MDXComponents;
onError?: React.ComponentType<{ error: Error }>;
}
```
### Use `evaluate` instead of `compileMDX`
**`🟥 next-mdx-remote`:**
The `compileMDX` takes `MDXRemoteProps` and returns `CompileMDXResult` as a promise.
```typescript
async function compileMDX<Frontmatter>({source, options, components}): Promise<CompileMDXResult> {}
```
The `compileMDX` takes one generic type parameter `<Frontmatter>`.
**`🟩 next-mdx-remote-client`:**
The `evaluate` takes `EvaluateProps` and returns `EvaluateResult` as a promise.
```typescript
async function evaluate<Frontmatter, Scope>({source, options, components}): Promise<EvaluateResult> {}
```
The `evaluate` takes two generic type parameters `<Frontmatter, Scope>` _(the order matters)_.
### The `evaluate` and the `compileMDX` have different results
**`🟥 next-mdx-remote`:**
The `compileMDX` returns the MDX `content` and the `frontmatter`.
```typescript
const { content, frontmatter } = await compileMDX<Frontmatter>({source, options, components});
type CompileMDXResult<TFrontmatter> = {
content: React.ReactElement
frontmatter: TFrontmatter
}
```
**`🟩 next-mdx-remote-client`:**
The `evaluate` returns `mod` object for the exports, `scope`, and `error` objects additional to MDX `content` and the `frontmatter`.
```typescript
const { content, mod, frontmatter, scope, error } = await evaluate<Frontmatter, Scope>({source, options, components});
type EvaluateResult<TFrontmatter, TScope> = {
content: React.JSX.Element;
mod: Record<string, unknown>;
frontmatter: TFrontmatter;
scope: TScope;
error?: Error;
}
```
### The differences in options
The `next-mdx-remote-client` has more options.
Please, note that, the `mdxOptions` are more or less similar in both **but have differences in terms of opinionation for `@mdx-js/mdx` options**.
**`🟥 next-mdx-remote`:**
The `compileMDX` and `MDXRemote` options:
```typescript
{
mdxOptions?: /* mdx options to be passed into @mdx-js/mdx */
parseFrontmatter?: boolean
scope?: Record<string, unknown>
}
```
**`🟩 next-mdx-remote-client`:**
The `evaluate` and `MDXRemote` options:
```typescript
{
mdxOptions?: /* mdx options to be passed into @mdx-js/mdx */
disableExports?: boolean; // <---
disableImports?: boolean; // <---
parseFrontmatter?: boolean;
scope?: Record<string, unknown>;
vfileDataIntoScope?: VfileDataIntoScope; // <---
}
```
## The part associated with Next.js `pages` router
_Go to [the part associated with Next.js app router](#the-part-associated-with-nextjs-app-router)_
### Serialize function takes named parameters and `rsc` parameter is removed
**`🟥 next-mdx-remote`:**
```typescript
const mdxSource = await serialize(source: VFileCompatible, options: SerializeOptions, rsc: boolean);
```
**`🟩 next-mdx-remote-client`:**
```typescript
const mdxSource = await serialize({ source: Compatible, options: SerializeOptions });
```
### Serialize function has additional options
**`🟥 next-mdx-remote`:**
```typescript
type SerializeOptions = {
mdxOptions?: SerializeMdxOptions;
parseFrontmatter?: boolean;
scope?: Record<string, unknown>;
};
```
**`🟩 next-mdx-remote-client`:**
```typescript
type SerializeOptions<TScope> = {
mdxOptions?: SerializeMdxOptions;
disableExports?: boolean; // <---
disableImports?: boolean; // <---
parseFrontmatter?: boolean;
scope?: TScope;
vfileDataIntoScope?: VfileDataIntoScope; // <---
};
```
### Serialize function accepts the generic type parameters in reverse
**`🟥 next-mdx-remote`:**
```typescript
const mdxSource = await serialize<Scope, Frontmatter>(/* */);
```
**`🟩 next-mdx-remote-client`:**
```typescript
const mdxSource = await serialize<Frontmatter, Scope>(/* */);
```
### SerializeResult takes the generic type parameters in reverse, as well
**`🟥 next-mdx-remote`:**
```typescript
type Props = {
mdxSource: MDXRemoteSerializeResult<Scope, Frontmatter>;
};
```
**`🟩 next-mdx-remote-client`:**
```typescript
type Props = {
mdxSource: SerializeResult<Frontmatter, Scope>;
};
```
### Serialize function returns "error" object
**`🟥 next-mdx-remote`:**
It has no "error" object in return.
```typescript
const { compiledSource, frontmatter, scope } = await serialize(/* */);
```
**`🟩 next-mdx-remote-client`:**
```typescript
const { compiledSource, frontmatter, scope, error } = await serialize(/* */);
```
### New function `hydrate`
**`🟥 next-mdx-remote`:**
_It doesn't have the function_
**`🟩 next-mdx-remote-client`:**
```typescript
const { content, mod, error } = hydrate(props: HydrateProps): HydrateResult {}
type HydrateProps = {
compiledSource: string;
frontmatter?: Record<string, unknown>;
scope?: Record<string, unknown>;
components?: MDXComponents;
disableParentContext?: boolean;
};
type HydrateResult = {
content: React.JSX.Element;
mod: Record<string, unknown>;
error?: Error;
};
```
### Use `MDXClient` instead of `MDXRemote` in "pages" router
**`🟥 next-mdx-remote`:**
```typescript
<MDXRemote
compiledSource={compiledSource}
frontmatter={frontmatter}
scope={scope}
components={components}
lazy={lazy} // boolean, optional
/>
```
**`🟩 next-mdx-remote-client`:**
```typescript
<MDXClient
compiledSource={compiledSource}
frontmatter={frontmatter}
scope={scope}
components={components}
onError={onError} // React.ComponentType<{ error: Error }>, optional
/>
```
### For lazy hydration use `hydrateLazy` or `<MDXClientLazy />`
**`🟥 next-mdx-remote`:**
```typescript
<MDXRemote
compiledSource={compiledSource}
// ..
lazy
/>
```
**`🟩 next-mdx-remote-client`:**
```typescript
const { content, mod, error } = hydrateLazy({compiledSource, /* */ })
```
or
```typescript
<MDXClientLazy
compiledSource={compiledSource}
// ..
/>
```
================================================
FILE: package.json
================================================
{
"name": "next-mdx-remote-client",
"description": "A wrapper of the `@mdx-js/mdx` for the `nextjs` applications in order to load MDX content. It is a fork of `next-mdx-remote`.",
"version": "2.1.10",
"type": "module",
"main": "./dist/csr/index.js",
"types": "./dist/csr/index.d.ts",
"exports": {
".": {
"types": "./dist/csr/index.d.ts",
"import": "./dist/csr/index.js",
"default": "./dist/csr/index.js"
},
"./csr": {
"types": "./dist/csr/index.d.ts",
"import": "./dist/csr/index.js",
"default": "./dist/csr/index.js"
},
"./serialize": {
"types": "./dist/csr/serialize.d.ts",
"import": "./dist/csr/serialize.js",
"default": "./dist/csr/serialize.js"
},
"./rsc": {
"types": "./dist/rsc/index.d.ts",
"import": "./dist/rsc/index.js",
"default": "./dist/rsc/index.js"
},
"./utils": {
"types": "./dist/utils/index.d.ts",
"import": "./dist/utils/index.js",
"default": "./dist/utils/index.js"
}
},
"scripts": {
"build": "rimraf dist && tsc --build && type-coverage",
"format": "npm run prettier && npm run lint",
"prettier": "prettier --write .",
"lint": "eslint .",
"pretest": "npm run build && npm pack --pack-destination ./dist",
"test:watch": "vitest --pool=vmThreads",
"test:file": "vitest --pool=vmThreads test.serialize-hydrate.spec.tsx",
"test": "npm run test:esm && npm run test:rest",
"test:esm": "vitest --pool=vmThreads run esm",
"test:rest": "vitest --pool=forks run --exclude 'tests/*esm*'",
"test-coverage": "vitest --pool=vmThreads run --coverage",
"prepublishOnly": "npm run format && npm run test-coverage"
},
"files": [
"dist/",
"LICENSE",
"README.md"
],
"repository": {
"type": "git",
"url": "git+https://github.com/ipikuka/next-mdx-remote-client.git"
},
"keywords": [
"markdown",
"MDX",
"@mdx-js/mdx",
"nextjs",
"next-mdx-remote",
"@next/mdx"
],
"author": "ipikuka <talatkuyuk@gmail.com>",
"license": "MPL 2.0",
"homepage": "https://github.com/ipikuka/next-mdx-remote-client#readme",
"bugs": {
"url": "https://github.com/ipikuka/next-mdx-remote-client/issues"
},
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@mdx-js/mdx": "^3.1.1",
"@mdx-js/react": "^3.1.1",
"remark-mdx-remove-esm": "^1.3.1",
"serialize-error": "^13.0.1",
"vfile": "^6.0.3",
"vfile-matter": "^5.0.1"
},
"devDependencies": {
"@eslint/js": "^9.39.3",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/babel__code-frame": "^7.27.0",
"@types/eslint-config-prettier": "^6.11.3",
"@types/mdx": "^2.0.13",
"@types/node": "^24.10.13",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react-swc": "^4.2.3",
"@vitest/coverage-v8": "^3.2.4",
"dedent": "^1.7.1",
"eslint": "^9.39.3",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-react": "^7.37.5",
"globals": "^17.3.0",
"jsdom": "^28.1.0",
"prettier": "^3.8.1",
"recma-mdx-change-props": "^1.2.4",
"recma-mdx-escape-missing-components": "^1.2.4",
"recma-mdx-import-react": "^1.2.4",
"remark-emoji": "^5.0.2",
"remark-flexible-markers": "^1.3.3",
"remark-flexible-paragraphs": "^1.3.3",
"rimraf": "^6.1.3",
"type-coverage": "^2.29.7",
"typescript": "^5.9.3",
"typescript-eslint": "^8.56.0",
"unified": "^11.0.5",
"vitest": "^3.2.4"
},
"peerDependencies": {
"react": ">= 19.1.0",
"react-dom": ">= 19.1.0"
},
"engines": {
"node": ">=20.9.0"
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"ignoreAsAssertion": true,
"ignoreCatch": true,
"strict": true
}
}
================================================
FILE: src/csr/MDXClient.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import type { MDXClientProps } from "./types.js";
import { hydrate } from "./hydrate.js";
/**
* renders the content on the client side (csr), which is provided by the "hydrate" function.
*/
export function MDXClient(props: MDXClientProps): React.JSX.Element {
const { onError: ErrorComponent, ...rest } = props;
const { content, error } = hydrate(rest);
if (error && !ErrorComponent) throw error;
if (error && ErrorComponent) return <ErrorComponent error={error} />;
return content;
}
================================================
FILE: src/csr/MDXClientAsync.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import type { MDXClientAsyncProps } from "./types.js";
import { hydrateAsync } from "./hydrateAsync.js";
/**
* it is experimental
*
* renders the content on the client side (csr), which is provided by the "hydrateAsync" function.
*
* the content is going to be hydrated "asynchronously" in a useEffect hook.
*/
export function MDXClientAsync(props: MDXClientAsyncProps): React.JSX.Element {
const { onError: ErrorComponent, ...rest } = props;
const { content, error } = hydrateAsync(rest);
/* v8 ignore next */
if (error && !ErrorComponent) throw error;
if (error && ErrorComponent) return <ErrorComponent error={error} />;
return content;
}
================================================
FILE: src/csr/MDXClientLazy.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import type { MDXClientProps } from "./types.js";
import { hydrateLazy } from "./hydrateLazy.js";
/**
* renders the content on the client side (csr), which is provided by the "hydrateLazy" function.
*
* the content is going to be hydrated "lazily".
*/
export function MDXClientLazy(props: MDXClientProps): React.JSX.Element {
const { onError: ErrorComponent, ...rest } = props;
const { content, error } = hydrateLazy(rest);
/* v8 ignore next */
if (error && !ErrorComponent) throw error;
if (error && ErrorComponent) return <ErrorComponent error={error} />;
return content;
}
================================================
FILE: src/csr/hydrate.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { MDXProvider, useMDXComponents } from "@mdx-js/react";
import { runSync } from "../lib/run.js";
import type { HydrateResult, HydrateProps } from "./types.js";
/**
* "run"s the javascript code in the compiled source, and
* returns the <Content /> component whether or not wrapped with the MDXProvider
* in the domain of client side rendering (csr).
*/
export function hydrate({
compiledSource,
frontmatter = {},
scope = {},
components,
disableParentContext,
}: HydrateProps): HydrateResult {
try {
const { Content, mod } = runSync(compiledSource, {
frontmatter,
scope,
mdxOptions: {
useMDXComponents,
},
});
const content = components ? (
// wrap the Content with the MDXProvider in order to customize the standard markdown components
<MDXProvider components={components} disableParentContext={disableParentContext}>
<Content />
</MDXProvider>
) : (
// no need to wrap the Content with the MDXProvider since there is no custom component provided
<Content />
);
return { content, mod };
} catch (error: unknown) {
return {
content: <div className="mdx-empty" />,
mod: {},
error: error as Error,
};
}
}
================================================
FILE: src/csr/hydrateAsync.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { useEffect, useState } from "react";
import { MDXProvider, useMDXComponents } from "@mdx-js/react";
import { runAsync } from "../lib/run.js";
import type { RunResult } from "../lib/types.js";
import type { HydrateAsyncProps, HydrateResult } from "./types.js";
/**
* This is experimental and proof for NOT WORKING in pages directory
*
* "run"s the javascript code in the compiled source, and
* returns the <Content /> component whether or not wrapped with the MDXProvider
* in the domain of client side rendering (csr).
*
* the hydration process occurs asynchronously in the useEffect so as to import modules in the compiled source.
*/
export function hydrateAsync({
compiledSource,
frontmatter = {},
scope = {},
components,
disableParentContext,
// two options below are for only hydrateAsync
options,
loading,
}: HydrateAsyncProps): HydrateResult {
const { baseUrl } = options ?? {};
const [runResult, setRunResult] = useState<RunResult | { error: Error }>({
Content: loading ? loading : () => <div />,
mod: {},
});
useEffect(() => {
async function getContent() {
// to see loading state a bit
await new Promise((resolve) => setTimeout(resolve, 500));
try {
const runResult_ = await runAsync(compiledSource, {
mdxOptions: {
baseUrl,
useMDXComponents,
},
frontmatter,
scope,
});
setRunResult(runResult_);
} catch (error) {
setRunResult({
error: error as Error,
});
}
}
getContent();
}, []);
if ("error" in runResult) {
return {
content: <div className="mdx-empty" />,
mod: {},
error: runResult.error,
};
}
const content = components ? (
// wrap the Content with the MDXProvider in order to customize the standard markdown components
<MDXProvider components={components} disableParentContext={disableParentContext}>
<runResult.Content />
</MDXProvider>
) : (
// no need to wrap the Content with the MDXProvider since there is no custom component provided
<runResult.Content />
);
return { content, mod: runResult.mod };
}
================================================
FILE: src/csr/hydrateLazy.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { useEffect, useMemo, useState } from "react";
import { MDXProvider, useMDXComponents } from "@mdx-js/react";
import "./idle-callback-polyfill.js";
import { runSync } from "../lib/run.js";
import type { HydrateResult, HydrateProps } from "./types.js";
/**
* "run"s the javascript code in the compiled source, and
* returns the <Content /> component whether or not wrapped with the MDXProvider
* in the domain of client side rendering (csr).
*
* the hydration process occurs lazily.
*/
export function hydrateLazy({
compiledSource,
frontmatter = {},
scope = {},
components,
disableParentContext,
}: HydrateProps): HydrateResult {
const [isReadyToRender, setIsReadyToRender] = useState(typeof window === "undefined");
// console.log({ isReadyToRender });
// since lazy, the mdx content is hydrated inside requestIdleCallback,
// allowing the page to get to interactive quicker, but the mdx content to hydrate slower.
useEffect(() => {
const request = window.requestIdleCallback(() => {
setIsReadyToRender(true);
});
return () => window.cancelIdleCallback(request);
}, []);
const { Content, mod, error } = useMemo(() => {
try {
const result = runSync(compiledSource, {
frontmatter,
scope,
mdxOptions: {
useMDXComponents,
},
});
return { ...result };
} catch (error) {
return { Content: () => <div className="mdx-empty" />, mod: {}, error: error as Error };
}
}, [compiledSource]);
if (!isReadyToRender) {
return {
// If not ready to render, return an empty div to preserve SSR'd markup
content: <div dangerouslySetInnerHTML={{ __html: "" }} suppressHydrationWarning />,
mod: {},
};
}
const content = components ? (
// wrap the Content with the MDXProvider in order to customize the standard markdown components
<MDXProvider components={components} disableParentContext={disableParentContext}>
<Content />
</MDXProvider>
) : (
// no need to wrap the Content with the MDXProvider since there is no custom component provided
<Content />
);
// since lazy, need to wrap with a div to preserve the same markup structure that was SSR'd
return { content: <div>{content}</div>, mod, error };
}
================================================
FILE: src/csr/idle-callback-polyfill.js
================================================
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*
* reference to https://github.com/hashicorp/next-mdx-remote/blob/main/src/idle-callback-polyfill.js
*/
if (typeof window !== "undefined") {
window.requestIdleCallback ||= function (cb) {
var start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
window.cancelIdleCallback ||= function (id) {
clearTimeout(id);
};
}
================================================
FILE: src/csr/index.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
export { hydrate } from "./hydrate.js";
export { hydrateLazy } from "./hydrateLazy.js";
export { hydrateAsync } from "./hydrateAsync.js";
export { MDXClient } from "./MDXClient.js";
export { MDXClientLazy } from "./MDXClientLazy.js";
export { MDXClientAsync } from "./MDXClientAsync.js";
export type {
HydrateProps,
HydrateResult,
MDXClientProps,
SerializeResult,
// below are experimantal
HydrateAsyncProps,
HydrateAsyncOptions,
MDXClientAsyncProps,
MDXClientAsyncOptions,
} from "./types.js";
// for who needs to use them without installing the "@mdx-js/react"
export { MDXProvider, useMDXComponents } from "@mdx-js/react";
// for who needs to use them without installing the "mdx/types"
export type { MDXComponents, MDXContent, MDXProps, MDXModule } from "mdx/types";
================================================
FILE: src/csr/requestIdleCallback.d.ts
================================================
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*
* reference to https://github.com/hashicorp/next-mdx-remote/blob/main/src/index.tsx
* requestIdleCallback types found here: https://github.com/microsoft/TypeScript/issues/21309
*/
type RequestIdleCallbackHandle = number;
type RequestIdleCallbackOptions = {
timeout?: number;
};
type RequestIdleCallbackDeadline = {
readonly didTimeout: boolean;
timeRemaining: () => number;
};
declare global {
interface Window {
requestIdleCallback: (
callback: (deadline: RequestIdleCallbackDeadline) => void,
opts?: RequestIdleCallbackOptions,
) => RequestIdleCallbackHandle;
cancelIdleCallback: (handle: RequestIdleCallbackHandle) => void;
}
}
================================================
FILE: src/csr/serialize.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { serializeError } from "serialize-error";
import type { CompileMdxOptions } from "../lib/types.js";
import { passVfileDataIntoScope } from "../lib/util.js";
import { prepare } from "../lib/prepare.js";
import { compile } from "../lib/compile.js";
import type { SerializeResult, SerializeProps, SerializeOptions } from "./types.js";
export type { SerializeResult, SerializeProps, SerializeOptions };
/**
* compiles the MDX source.
*
* the compiled source can be passed into "<MDXClient />" or "hydrate" to be rendered on the client side (csr).
*
*/
export async function serialize<
TFrontmatter extends Record<string, unknown> = Record<string, unknown>,
TScope extends Record<string, unknown> = Record<string, unknown>,
>({
source,
options = {},
}: SerializeProps<TScope>): Promise<SerializeResult<TFrontmatter, TScope>> {
const {
mdxOptions = {},
disableExports,
disableImports,
parseFrontmatter,
scope = {} as TScope,
vfileDataIntoScope,
} = options;
const { vfile, frontmatter } = prepare<TFrontmatter>(source, parseFrontmatter);
const compileMDXOptions: CompileMdxOptions = {
...mdxOptions,
providerImportSource: "#", // important! doesn't matter "@mdx-js/react" since the outputFormat is "function-body"
};
try {
const { compiledSource } = await compile(vfile, {
mdxOptions: compileMDXOptions,
disableExports,
disableImports,
});
if (vfileDataIntoScope)
passVfileDataIntoScope(compiledSource.data, vfileDataIntoScope, scope);
return {
compiledSource: String(compiledSource),
frontmatter,
scope,
};
} catch (error: unknown) {
return {
error: serializeError(error) as Error,
frontmatter,
scope,
};
}
}
================================================
FILE: src/csr/types.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import type {
CompileOptions as OriginalCompileOptions,
RunOptions as OriginalRunOptions,
} from "@mdx-js/mdx";
import type { MDXComponents } from "mdx/types";
import type { Compatible } from "vfile";
import type { VfileDataIntoScope } from "../lib/util.js";
export type Prettify<T> = { [K in keyof T]: T[K] } & {};
export type SerializeProps<TScope extends Record<string, unknown> = Record<string, unknown>> = {
/**
* markdown or MDX source.
*/
source: Compatible;
/**
* serialize options.
*/
options?: SerializeOptions<TScope>;
};
export type SerializeOptions<TScope extends Record<string, unknown> = Record<string, unknown>> =
{
/**
* These options are passed to the MDX compiler.
* See [the MDX docs.](https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js).
*/
mdxOptions?: SerializeMdxOptions;
/**
* Whether or not strip out "export"s from MDX. Defaults to false, which means it does NOT strip out.
*/
disableExports?: boolean;
/**
* Whether or not strip out "import"s from MDX. Defaults to false, which means it does NOT strip out.
*/
disableImports?: boolean;
/**
* Indicates whether or not the frontmatter should be parsed out of the MDX. Defaults to false.
*/
parseFrontmatter?: boolean;
/**
* An arbitrary object of data which will be supplied to the MDX.
*
* For example, in cases where you want to provide template variables to the MDX, like `my name is {name}`,
* you could provide scope as `{ name: "Some name" }`.
*/
scope?: TScope;
/**
* Compiled source vfile.data may hold some extra information.
* Some field names in vfile.data may be needed to pass into the scope.
* If you need to change the name of the field, specify it { name: string; as: string } while passing.
* if the scope has the same key already, vfile.data overrides it.
*/
vfileDataIntoScope?: VfileDataIntoScope;
};
type SerializeMdxOptions = Omit<
OriginalCompileOptions,
"outputFormat" | "providerImportSource"
>;
export type SerializeResult<
TFrontmatter = Record<string, unknown>,
TScope = Record<string, unknown>,
> = Prettify<
(
| {
/**
* The compiledSource, generated from the serialize function
*/
compiledSource: string;
}
| {
/**
* The formatted MDX error object if compilation of the source is failed.
*/
error: Error;
}
) & {
/**
* If parseFrontmatter was set to true, contains any parsed frontmatter found in the MDX source.
*/
frontmatter: TFrontmatter;
/**
* An arbitrary object of data which will be supplied to the MDX.
*
* For example, in cases where you want to provide template variables to the MDX, like `my name is {name}`,
* you could provide scope as `{ name: "Some name" }`.
*/
scope: TScope;
}
>;
export type HydrateProps = {
/**
* The compiledSource, generated from the serialize function
*/
compiledSource: string;
/**
* If parseFrontmatter was set to true, contains any parsed frontmatter found in the MDX source.
*/
frontmatter?: Record<string, unknown>;
/**
* Indicates whether or not the frontmatter should be parsed out of the MDX. Defaults to false.
*/
scope?: Record<string, unknown>;
/**
* An object mapping names to React components.
* The key used will be the name accessible to MDX.
*
* For example: `{ ComponentName: Component }` will be accessible in the MDX as `<ComponentName/>`.
*/
components?: MDXComponents;
/**
* Disable parent context
*
* @see https://github.com/mdx-js/mdx/blob/8f754f707207915bd34c3af8f9064e367c125a58/packages/react/lib/index.js#L70
*/
disableParentContext?: boolean;
};
export type HydrateResult = {
/**
* React element that renders the MDX compiled source using the component names mapping object.
*/
content: React.JSX.Element;
/**
* An object which holds any value that is exported from the MDX file.
*/
mod: Record<string, unknown> | { [key: string]: never };
/**
* The error object if construction of the compiled source is failed.
*/
error?: Error;
};
export type MDXClientProps = Prettify<
HydrateProps & {
onError?: React.ComponentType<{ error: Error }>;
}
>;
export type HydrateAsyncProps = Prettify<
HydrateProps & {
/**
* hydrate options which is experimental for hydrateAsync only. It is INEFFECTIVE for hydrate and hydrateLazy.
*/
options?: HydrateAsyncOptions;
/**
* fallback loading component
*/
loading?: () => React.JSX.Element;
}
>;
export type HydrateAsyncOptions = {
/**
* All RunOptions are pre-defined except the "baseUrl"
*/
baseUrl?: OriginalRunOptions["baseUrl"];
};
export type MDXClientAsyncProps = Prettify<
HydrateAsyncProps & {
onError?: React.ComponentType<{ error: Error }>;
}
>;
export type MDXClientAsyncOptions = HydrateAsyncOptions;
================================================
FILE: src/lib/compile.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { compile as compileMDX, type CompileOptions as CompileMDXOptions } from "@mdx-js/mdx";
import type { VFile } from "vfile";
import type { PluggableList } from "unified";
import remarkMdxRemoveEsm from "remark-mdx-remove-esm";
import type { CompileOptions, CompileResult } from "./types.js";
import { createFormattedMDXError } from "./util.js";
/**
* composes an opinionated version of CompileOptions of the "@mdx-js/mdx"
*
* @param options CompileOptions
* @returns CompileOptions of the "@mdx-js/mdx"
*/
function composeCompileOptions(options: CompileOptions = {}): CompileMDXOptions {
const { mdxOptions = {}, disableImports, disableExports } = options;
const mdxRemoveEsmOptions = [disableExports && "export", disableImports && "import"];
const remarkPlugins: PluggableList = [
...(mdxOptions.remarkPlugins || []),
[remarkMdxRemoveEsm, mdxRemoveEsmOptions],
];
return {
...mdxOptions,
remarkPlugins,
outputFormat: "function-body",
};
}
/**
* compiles the vfile source via the compile of the "@mdx-js/mdx".
*
* returns the compiled source.
*/
export async function compile(vfile: VFile, options?: CompileOptions): Promise<CompileResult> {
try {
const compiledSource = await compileMDX(vfile, composeCompileOptions(options));
// for debugging
if (options?.debugCompiledSource) {
console.log(String(compiledSource));
}
// await new Promise((resolve) => setTimeout(resolve, 500));
return {
compiledSource,
};
} catch (error: any) {
throw createFormattedMDXError(error, String(vfile));
}
}
================================================
FILE: src/lib/prepare.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { type Compatible, VFile } from "vfile";
import { matter } from "vfile-matter";
import type { PrepareResult } from "./types.js";
/**
* turns the source into vfile, gets the fronmatter, strips it out from the vfile
*
* @param source markdown or MDX source
* @param parseFrontmatter indicates whether or not the frontmatter should be parsed out of the source
* @returns the frontmatter and stripped vfile
*/
export function prepare<TFrontmatter extends Record<string, unknown> = Record<string, unknown>>(
source: Compatible,
parseFrontmatter?: boolean,
): PrepareResult<TFrontmatter> {
const vfile = looksLikeAVFile(source) ? source : new VFile(source);
// makes frontmatter available via vfile.data.matter
if (parseFrontmatter) matter(vfile, { strip: true });
const frontmatter = (vfile.data.matter ?? {}) as TFrontmatter;
return {
vfile,
frontmatter,
};
}
/**
* taken from @mdx-js/mdx/lib/util/resolve-file-and-options.js
*/
function looksLikeAVFile(value?: Compatible): value is VFile {
return Boolean(
value && typeof value === "object" && "message" in value && "messages" in value,
);
}
================================================
FILE: src/lib/run.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import * as React from "react";
import * as jsxRuntime from "react/jsx-runtime";
import * as jsxDevRuntime from "react/jsx-dev-runtime";
import type { MDXModule } from "mdx/types";
import type { Fragment, Jsx, JsxDev } from "@mdx-js/mdx";
import type { RunOptions, RunResult } from "./types.js";
type JsxRuntime = {
Fragment: Fragment;
jsx: Jsx;
jsxs: Jsx;
};
type JsxDevRuntime = {
Fragment: Fragment;
jsxDEV: JsxDev;
};
// TODO: use run and runSync function from "@mdx-js/mdx"
/**
* creates an object to be used for the function construction
*
* @param options RunOptions
* @returns keys and values of the object
*/
function prepareConstruction(options: RunOptions) {
const constructionScope = {
runMdxOptions: {
useMDXComponents: options.mdxOptions?.useMDXComponents,
baseUrl: options.mdxOptions?.baseUrl,
jsx: (jsxRuntime as JsxRuntime).jsx,
jsxs: (jsxRuntime as JsxRuntime).jsxs,
jsxDEV: (jsxDevRuntime as JsxDevRuntime).jsxDEV,
Fragment: (jsxRuntime as JsxRuntime).Fragment, // doesn't matter
React,
},
frontmatter: options.frontmatter,
...options.scope,
};
return {
keys: Object.keys(constructionScope),
values: Object.values(constructionScope),
};
}
/**
* parses and runs the javascript code syncronously in the compiled MDX source.
*/
export function runSync(compiledSource: string, options: RunOptions): RunResult {
const { keys, values } = prepareConstruction(options);
/* v8 ignore next */
const SyncFunction = function () {}.constructor;
// constructs the compiled source utilizing Reflect API with "function constructor"
const hydrateFn: typeof SyncFunction = Reflect.construct(
SyncFunction,
keys.concat(compiledSource),
);
const { default: Content, ...mod } = hydrateFn(...values) as MDXModule;
return { Content, mod };
}
/**
* parses and runs the javascript code asyncronously in the compiled MDX source.
*/
export async function runAsync(
compiledSource: string,
options: RunOptions,
): Promise<RunResult> {
const { keys, values } = prepareConstruction(options);
/* v8 ignore next */
const AsyncFunction = async function () {}.constructor;
// await new Promise((resolve) => setTimeout(resolve, 500));
// constructs the compiled source utilizing Reflect API with "async function constructor"
const hydrateFn: typeof AsyncFunction = Reflect.construct(
AsyncFunction,
keys.concat(compiledSource),
);
const { default: Content, ...mod } = await (hydrateFn(...values) as Promise<MDXModule>);
return { Content, mod };
}
================================================
FILE: src/lib/types.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import type {
CompileOptions as OriginalCompileOptions,
RunOptions as OriginalRunOptions,
} from "@mdx-js/mdx";
import type { MDXContent } from "mdx/types";
import type { Compatible, VFile } from "vfile";
export type PrepareProps = {
/**
* the markdown or mdx source.
*/
source: Compatible;
/**
* Indicates whether or not the frontmatter should be parsed out of the MDX. Defaults to false.
*/
parseFrontmatter?: boolean;
};
export type PrepareResult<TFrontmatter = Record<string, unknown>> = {
/**
* the converted vFile of the source for compile function.
*/
vfile: VFile;
/**
* the parsed frontmatter found in the MDX source if parseFrontmatter is set to true.
*/
frontmatter: TFrontmatter;
};
export type CompileOptions = {
/**
* These options are passed to the MDX compiler.
* See [the MDX docs.](https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js).
*/
mdxOptions?: CompileMdxOptions;
/**
* Whether or not strip out "export"s from MDX. Defaults to false, which means it does NOT strip out.
*/
disableExports?: boolean;
/**
* Whether or not strip out "import"s from MDX. Defaults to false, which means it does NOT strip out.
*/
disableImports?: boolean;
/**
* for debugging
*/
debugCompiledSource?: boolean;
};
export type CompileMdxOptions = Omit<OriginalCompileOptions, "outputFormat">;
export type RunOptions = {
/**
* These options are passed to the MDX compiler.
* See [the MDX docs.](https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js).
*/
mdxOptions?: RunMdxOptions;
/**
* the parsed frontmatter found in the MDX source if parseFrontmatter is set to true.
*/
frontmatter: Record<string, unknown> | { [key: string]: never };
/**
* An arbitrary object of data which will be supplied to the MDX.
*/
scope: Record<string, unknown> | { [key: string]: never };
};
export type RunMdxOptions = Omit<OriginalRunOptions, "Fragment" | "jsx" | "jsxDEV" | "jsxs">;
export type CompileResult = {
/**
* compiled source produced by the serialize function, which contains js code in string format.
*/
compiledSource: VFile;
};
export type RunResult = {
/**
* A functional JSX component which renders the content of the MDX file.
*/
Content: MDXContent;
/**
* An object which holds any value that is exported from the MDX file.
*/
mod: {
[key: string]: unknown;
};
};
================================================
FILE: src/lib/util.ts
================================================
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*
* reference to https://github.com/hashicorp/next-mdx-remote/blob/main/src/format-mdx-error.ts
*
* improved the types
*/
import { codeFrameColumns, type SourceLocation } from "@babel/code-frame";
/**
* Attempt to parse position information from an error message originating from the MDX compiler.
*
* @param message error message
* @returns the position of the error indicator
*/
function parsePositionInformationFromErrorMessage(message: string): SourceLocation | undefined {
const positionInfoPattern = /\d+:\d+(-\d+:\d+)/g;
const match = message.match(positionInfoPattern);
if (!match) return;
// take the last match, that seems to be the most reliable source of the error.
const lastMatch = match.slice(-1)[0];
const [line, column] = lastMatch.split("-")[0].split(":");
return {
start: {
line: Number.parseInt(line, 10),
column: Number.parseInt(column, 10),
},
};
}
/**
* prints a nicely formatted error message from an error caught during MDX compilation.
*
* @param error Error caught from the mdx compiler
* @param source Raw MDX string
* @returns Error
*/
export function createFormattedMDXError(error: Error, source: string): Error {
const position =
"position" in error && Boolean(error.position)
? (error.position as SourceLocation)
: parsePositionInformationFromErrorMessage(error.message);
const codeFrames =
position?.start?.line !== undefined
? codeFrameColumns(source, position, { linesAbove: 2, linesBelow: 2 })
: "";
const formattedError = new Error(`[next-mdx-remote-client] error compiling MDX:
${error.message}
${codeFrames ? "\n" + codeFrames + "\n" : ""}
More information: https://mdxjs.com/docs/troubleshooting-mdx`);
// commented since React Flight throws an error if error stack is mutated
// when the error object is a prop in a rsc
// formattedError.stack = "";
return formattedError;
}
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
export type VfileDataIntoScope =
| true // all fields
| string // one specific field
| { name: string; as: string } // one specific field but change the key as
| Array<string | { name: string; as: string }>; // more than one field
/**
* copies some fields of vfile.data into scope by mutating the scope
* pay attention that it provides reference copy for objects (including arrays)
*
* @param data vfile.data from copied
* @param vfileDataIntoScope refers the fields of vfile.data, some or all (if true)
* @param scope an object to copied in a mutable way
*/
export function passVfileDataIntoScope(
data: Record<string, unknown>,
vfileDataIntoScope: VfileDataIntoScope,
scope: Record<string, unknown>,
): undefined {
if (typeof vfileDataIntoScope === "boolean") {
Object.entries(data).forEach(([key, value]) => {
scope[key] = value;
});
} else if (typeof vfileDataIntoScope === "string") {
scope[vfileDataIntoScope] = data[vfileDataIntoScope];
} else if (Array.isArray(vfileDataIntoScope)) {
vfileDataIntoScope.forEach((field) => {
if (typeof field === "string") {
scope[field] = data[field];
} else if (
// type-coverage:ignore-next-line
Object.prototype.hasOwnProperty.call(field, "name") &&
// type-coverage:ignore-next-line
Object.prototype.hasOwnProperty.call(field, "as")
) {
scope[field.as] = data[field.name];
}
});
} else if (
// type-coverage:ignore-next-line
Object.prototype.hasOwnProperty.call(vfileDataIntoScope, "name") &&
// type-coverage:ignore-next-line
Object.prototype.hasOwnProperty.call(vfileDataIntoScope, "as")
) {
scope[vfileDataIntoScope.as] = data[vfileDataIntoScope.name];
}
}
================================================
FILE: src/rsc/MDXRemote.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { evaluate } from "./evaluate.js";
import type { MDXRemoteProps } from "./types.js";
/**
* renders the content as a react server component (rsc), which is provided by the "evaluate" function
*/
export async function MDXRemote(props: MDXRemoteProps): Promise<React.JSX.Element> {
const { onError: ErrorComponent, ...rest } = props;
const { content, error } = await evaluate(rest);
if (error && !ErrorComponent) throw error;
if (error && ErrorComponent) return <ErrorComponent error={error} />;
return content;
}
================================================
FILE: src/rsc/evaluate.tsx
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { compile } from "../lib/compile.js";
import { prepare } from "../lib/prepare.js";
import { runSync, runAsync } from "../lib/run.js";
import { passVfileDataIntoScope } from "../lib/util.js";
import type { EvaluateProps, EvaluateResult } from "./types.js";
/**
* "compiles" the MDX source and "runs" the javascript code in the compiled source, so it basically "evaluates" the MDX.
*
* returns the frontmatter, exported object and the react server component to be rendered on the server.
*
*/
export async function evaluate<
TFrontmatter extends Record<string, unknown> = Record<string, unknown>,
TScope extends Record<string, unknown> = Record<string, unknown>,
>({
source,
options = {},
components = {},
}: EvaluateProps<TScope>): Promise<EvaluateResult<TFrontmatter, TScope>> {
const {
mdxOptions = {},
disableExports,
disableImports,
scope = {} as TScope,
parseFrontmatter,
vfileDataIntoScope,
debug,
} = options;
const { vfile, frontmatter } = prepare<TFrontmatter>(source, parseFrontmatter);
const { baseUrl, ...compileMDXOptions } = mdxOptions;
try {
const { compiledSource } = await compile(vfile, {
mdxOptions: compileMDXOptions,
disableExports,
disableImports,
debugCompiledSource: debug?.compiledSource,
});
if (vfileDataIntoScope)
passVfileDataIntoScope(compiledSource.data, vfileDataIntoScope, scope);
// This check is necessary otherwise "await" expression in the compiledSource throws a syntax error
const { Content, mod } = disableImports
? runSync(String(compiledSource), {
frontmatter,
scope,
})
: await runAsync(String(compiledSource), {
mdxOptions: { baseUrl },
frontmatter,
scope,
});
return {
content: <Content components={components} />,
mod,
frontmatter,
scope,
};
} catch (error: unknown) {
return {
content: <div className="mdx-empty" />,
mod: {},
frontmatter: frontmatter as TFrontmatter,
scope,
error: error as Error,
};
}
}
================================================
FILE: src/rsc/index.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
export { MDXRemote } from "./MDXRemote.js";
export { evaluate } from "./evaluate.js";
export type {
MDXRemoteProps,
MDXRemoteOptions,
EvaluateProps,
EvaluateOptions,
EvaluateResult,
} from "./types.js";
// for who needs to use them without installing the "mdx/types"
export type { MDXComponents, MDXContent, MDXProps, MDXModule } from "mdx/types";
================================================
FILE: src/rsc/types.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import type { EvaluateOptions as OriginalEvaluateOptions } from "@mdx-js/mdx";
import type { MDXComponents } from "mdx/types";
import type { Compatible } from "vfile";
import type { VfileDataIntoScope } from "../lib/util.js";
export type Prettify<T> = { [K in keyof T]: T[K] } & {};
export type EvaluateProps<TScope extends Record<string, unknown> = Record<string, unknown>> = {
/**
* markdown or MDX source.
*/
source: Compatible;
/**
* evaluate options.
*/
options?: EvaluateOptions<TScope>;
/**
* An object mapping names to React components.
* The key used will be the name accessible to MDX.
*
* For example: `{ ComponentName: Component }` will be accessible in the MDX as `<ComponentName/>`.
*/
components?: MDXComponents;
};
export type EvaluateOptions<TScope extends Record<string, unknown> = Record<string, unknown>> =
{
/**
* These options are passed to the MDX compiler.
* See [the MDX docs.](https://github.com/mdx-js/mdx/blob/master/packages/mdx/index.js).
*/
mdxOptions?: EvaluateMdxOptions;
/**
* Whether or not strip out "export"s from MDX. Defaults to false, which means it does NOT strip out.
*/
disableExports?: boolean;
/**
* Whether or not strip out "import"s from MDX. Defaults to false, which means it does NOT strip out.
*/
disableImports?: boolean;
/**
* Indicates whether or not the frontmatter should be parsed out of the MDX. Defaults to false.
*/
parseFrontmatter?: boolean;
/**
* An arbitrary object of data which will be supplied to the MDX.
*
* For example, in cases where you want to provide template variables to the MDX, like `my name is {name}`,
* you could provide scope as `{ name: "Some name" }`.
*/
scope?: TScope;
/**
* Compiled source vfile.data may hold some extra information.
* Some field names in vfile.data may be needed to pass into the scope.
* If you need to change the name of the field, specify it { name: string; as: string } while passing.
* if the scope has the same key already, vfile.data overrides it.
*/
vfileDataIntoScope?: VfileDataIntoScope;
/**
* for debugging
*/
debug?: {
compiledSource?: boolean;
};
};
type EvaluateMdxOptions = Omit<
OriginalEvaluateOptions,
| "Fragment"
| "jsx"
| "jsxs"
| "jsxDEV"
| "useMDXComponents"
| "providerImportSource"
| "outputFormat"
>;
export type EvaluateResult<
TFrontmatter = Record<string, unknown>,
TScope = Record<string, unknown>,
> = {
/**
* React element that renders the MDX source using the component names mapping object.
*/
content: React.JSX.Element;
/**
* An object which holds any value that is exported from the MDX file.
*/
mod: Record<string, unknown> | { [key: string]: never };
/**
* the parsed frontmatter found in the MDX source if parseFrontmatter is set to true.
*/
frontmatter: TFrontmatter;
/**
* The scope can be mutated during the compile process, and you may want to get it back.
*
*/
scope: TScope;
/**
* The error object if construction of the compiled source is failed, or
* compilation of the source is failed due to MDX syntax error.
*/
error?: Error;
};
export type MDXRemoteProps = Prettify<
EvaluateProps & {
onError?: React.ComponentType<{ error: Error }>;
}
>;
export type MDXRemoteOptions = EvaluateOptions;
================================================
FILE: src/utils/getFrontmatter.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
import { type Compatible, VFile } from "vfile";
import { matter } from "vfile-matter";
/**
* gets the fronmatter and the stripped source
*
* @param source markdown or MDX source
* @returns fronmatter and stripped source. If no matter is found, the frontmatter is an empty object.
*/
export function getFrontmatter<TFrontmatter extends Record<string, unknown>>(
source: Compatible,
): { frontmatter: TFrontmatter; strippedSource: string } {
const vfile = new VFile(source);
matter(vfile, { strip: true });
const frontmatter = vfile.data.matter as TFrontmatter;
// If no matter is found, the file.data.matter is an empty object ({}).
return { frontmatter, strippedSource: String(vfile) };
}
================================================
FILE: src/utils/index.ts
================================================
/**
* Copyright (c) @talatkuyuk AKA @ipikuka
* SPDX-License-Identifier: MPL-2.0
*/
// for who needs to parse and get the fronmatter and stripped source
export { getFrontmatter } from "./getFrontmatter.js";
================================================
FILE: tests/ErrorBoundaryClassic.jsx
================================================
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
// Define a state variable to track whether is an error or not
this.state = { hasError: false };
}
// eslint-disable-next-line no-unused-vars
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log({ error, errorInfo });
}
render() {
// Check if the error is thrown
if (this.state.hasError) {
// You can render any custom fallback UI
return (
<div>
<h2>Oops, there is an error!</h2>
<button type="button" onClick={() => this.setState({ hasError: false })}>
Try again?
</button>
</div>
);
}
// Return children components in case of no error
return this.props.children;
}
}
export default ErrorBoundary;
================================================
FILE: tests/ErrorBoundaryForTests.tsx
================================================
import React from "react";
interface ErrorBoundaryProps {
fallback: React.ReactNode;
onError?: (error: Error, info: React.ErrorInfo) => void;
children: React.ReactNode;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}
/**
* a TypeScript-based ErrorBoundary that gives a reliable runtime error
* since React will stop propagating those “uncatchable” render errors once they’re caught by boundary
*/
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
this.props.onError?.(error, info);
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
================================================
FILE: tests/context/ExampleForm.mjs
================================================
import { useId, useState } from "react";
function ExampleForm() {
const id = useId(); // Generates a unique ID
const [name, setName] = useState("");
return (
<div>
<label htmlFor={`${id}-name`}>Enter your name:</label>
<input
id={`${id}-name`}
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Hello, {name || "stranger"}!</p>
</div>
);
}
export default ExampleForm;
================================================
FILE: tests/context/ExampleFormTransformedAutomatic.mjs
================================================
import { useId, useState } from "react";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function ExampleForm() {
const id = useId(); // Generates a unique ID
const [name, setName] = useState("");
return /*#__PURE__*/ _jsxs("div", {
children: [
/*#__PURE__*/ _jsx("label", {
htmlFor: `${id}-name`,
children: "Enter your name:",
}),
/*#__PURE__*/ _jsx("input", {
id: `${id}-name`,
type: "text",
value: name,
onChange: (e) => setName(e.target.value),
}),
/*#__PURE__*/ _jsxs("p", {
children: ["Hello, ", name || "stranger", "!"],
}),
],
});
}
export default ExampleForm;
================================================
FILE: tests/context/ExampleFormTransformedClassic.mjs
================================================
import React, { useId, useState } from "react";
function ExampleForm() {
const id = useId(); // Generates a unique ID
const [name, setName] = useState("");
return /*#__PURE__*/ React.createElement(
"div",
null,
/*#__PURE__*/ React.createElement(
"label",
{
htmlFor: `${id}-name`,
},
"Enter your name:",
),
/*#__PURE__*/ React.createElement("input", {
id: `${id}-name`,
type: "text",
value: name,
onChange: (e) => setName(e.target.value),
}),
/*#__PURE__*/ React.createElement("p", null, "Hello, ", name || "stranger", "!"),
);
}
export default ExampleForm;
================================================
FILE: tests/context/HelloDave.mjs
================================================
import * as ReactModule from "react";
export default function HelloDave({ runtimeProps, ...props }) {
const { React = ReactModule } = runtimeProps;
if (!React) return "<HelloDave /> component doesn't work due to missing `React` instance !";
const id = React.useId();
return React.createElement("div", props, `Hello, Dave! Your id is ${id}`);
}
================================================
FILE: tests/context/components.js
================================================
// the same test file taken from @mdx-js/mdx test files iot be inline with
import React from "react";
/**
* @param {Readonly<React.JSX.IntrinsicElements['span']>} props
* Props
* @returns
* `span` element.
*/
export function Pill(props) {
return React.createElement("span", { ...props, style: { color: "blue" } });
}
/**
* @param {Readonly<React.JSX.IntrinsicElements['div']>} props
* Props
* @returns
* `div` element.
*/
export function Layout(props) {
return React.createElement("div", { ...props, style: { color: "red" } });
}
export default Layout;
================================================
FILE: tests/context/data.js
================================================
// the same test file taken from @mdx-js/mdx test files iot be inline with
/**
* Number.
*/
export const number = 3.14;
/**
* Object.
*/
export const object = { a: 1, b: 2 };
/**
* Array.
*/
export const array = [1, 2];
/**
* Number.
*/
export default 2 * number;
================================================
FILE: tests/test.MDXClient.spec.tsx
================================================
import { describe, expect, test } from "vitest";
import ReactDOMServer from "react-dom/server";
import { MDXClient } from "../src/csr";
import { serialize } from "../src/csr/serialize.js";
import { ErrorBoundary } from "./ErrorBoundaryForTests.js";
describe("MDXClient", () => {
test("works", async () => {
const mdxSource = await serialize({
source: "hi <Test name={bar} />",
options: {
scope: {
bar: "ipikuka",
},
},
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
const components = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
};
expect(
ReactDOMServer.renderToStaticMarkup(<MDXClient components={components} {...mdxSource} />),
).toMatchInlineSnapshot(`"<p>hi <strong>ipikuka</strong></p>"`);
});
test("works with catchable errors", async () => {
const mdxSource = await serialize({
source: "import x from 'y'",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
const onError = ({ error }: { error: Error }) => {
return <div>{error.message}</div>;
};
expect(() =>
ReactDOMServer.renderToStaticMarkup(<MDXClient {...mdxSource} />),
).toThrowErrorMatchingInlineSnapshot(
`[SyntaxError: await is only valid in async functions and the top level bodies of modules]`,
);
expect(
ReactDOMServer.renderToStaticMarkup(<MDXClient {...mdxSource} onError={onError} />),
).toMatchInlineSnapshot(
`"<div>await is only valid in async functions and the top level bodies of modules</div>"`,
);
});
test("has problem working with uncatchable errors", async () => {
const mdxSource = await serialize({
source: "hi {bar}",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
const onError = ({ error }: { error: Error }) => {
return <div>{error.message}</div>;
};
// throws error only during render
expect(() =>
ReactDOMServer.renderToStaticMarkup(<MDXClient {...mdxSource} />),
).toThrowErrorMatchingInlineSnapshot(`[ReferenceError: bar is not defined]`);
// even the ErrorBoundary couldn't catch the error, don't know why?
expect(() =>
ReactDOMServer.renderToStaticMarkup(
<ErrorBoundary
fallback={<div data-testid="mdx-error">Something went wrong</div>}
onError={(error) => {
console.log(error);
}}
>
<MDXClient {...mdxSource} onError={onError} />
</ErrorBoundary>,
),
).toThrowErrorMatchingInlineSnapshot(`[ReferenceError: bar is not defined]`);
});
});
================================================
FILE: tests/test.MDXClientAsync.esm.spec.tsx
================================================
import { vi, describe, expect, test } from "vitest";
import type { ComponentProps } from "react";
import { render, screen, waitFor } from "@testing-library/react";
import { MDXClientAsync, type MDXComponents } from "../src/csr";
import { serialize } from "../src/csr/serialize.js";
import { ErrorBoundary } from "./ErrorBoundaryForTests.js";
describe("MDXClientAsync", () => {
const LoadingComponent = () => {
return <div data-testid="mdx-loading">loading</div>;
};
const ErrorComponent = ({ error }: { error: Error }) => {
return <div data-testid="mdx-error">{error.message}</div>;
};
const mdxComponents = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
wrapper: (props: ComponentProps<"div"> & { components: MDXComponents }) => {
const { components, children, ...rest } = props; // eslint-disable-line @typescript-eslint/no-unused-vars
return (
<div data-testid="mdx-layout" {...rest}>
{children}
</div>
);
},
};
test("works as expected", async () => {
const mdxSource = await serialize({
source: "hi <Test name={bar} />",
options: {
scope: {
bar: "ipikuka",
},
},
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
render(
<MDXClientAsync
components={mdxComponents}
{...mdxSource}
loading={LoadingComponent}
onError={ErrorComponent}
/>,
);
const loadingDiv = screen.queryByTestId("mdx-loading");
expect(loadingDiv?.innerHTML).toEqual("loading");
await waitFor(() => {
const layoutDiv = screen.queryByTestId("mdx-layout");
expect(layoutDiv?.innerHTML).toContain("<p>hi <strong>ipikuka</strong></p>");
});
});
test("works with catchable errors 1", async () => {
const mdxSource = await serialize({
source: "import x from 'y'",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
render(
<MDXClientAsync
components={mdxComponents}
{...mdxSource}
loading={LoadingComponent}
onError={ErrorComponent}
/>,
);
const loadingDiv = screen.queryByTestId("mdx-loading");
expect(loadingDiv?.innerHTML).toEqual("loading");
await screen.findByTestId("mdx-error", {}, { timeout: 2000 });
expect(screen.queryByTestId("mdx-error")).toMatchInlineSnapshot(`
<div
data-testid="mdx-error"
>
Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`
</div>
`);
});
test("works with catchable errors 2", async () => {
const mdxSource = await serialize({
source: "import x from 'y'",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
render(
<MDXClientAsync
components={mdxComponents}
{...mdxSource}
loading={LoadingComponent}
onError={ErrorComponent}
options={{ baseUrl: "https://gist.githubusercontent.com/Bar.mjs" }}
/>,
);
const loadingDiv = screen.queryByTestId("mdx-loading");
expect(loadingDiv?.innerHTML).toEqual("loading");
await screen.findByTestId("mdx-error", {}, { timeout: 2000 });
expect(screen.queryByTestId("mdx-error")?.innerHTML).toContain(
"Cannot find package 'y' imported from",
);
});
test("uncatchable runtime error", async () => {
const mdxSource = await serialize({
source: "hi {bar}",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const onError = vi.fn();
render(
<ErrorBoundary
fallback={<div data-testid="mdx-error">Something went wrong</div>}
onError={onError}
>
<MDXClientAsync
components={mdxComponents}
{...mdxSource}
loading={LoadingComponent}
onError={ErrorComponent}
/>
</ErrorBoundary>,
);
const loadingDiv = screen.queryByTestId("mdx-loading");
expect(loadingDiv).toHaveTextContent("loading");
expect(loadingDiv?.innerHTML).toEqual("loading");
await waitFor(() =>
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
name: "ReferenceError",
message: expect.stringContaining("bar is not defined"),
}),
expect.objectContaining({
componentStack: expect.stringContaining("_createMdxContent"),
}),
),
);
const errorDiv = await screen.findByTestId("mdx-error", {}, { timeout: 2000 });
expect(errorDiv).toHaveTextContent("Something went wrong");
expect(errorDiv.innerHTML).toEqual("Something went wrong");
expect(consoleErrorSpy).toHaveBeenCalled();
consoleErrorSpy.mockRestore();
});
});
================================================
FILE: tests/test.MDXClientLazy.spec.tsx
================================================
import { vi, describe, expect, test } from "vitest";
import type { ComponentProps } from "react";
import { render, screen, waitFor } from "@testing-library/react";
import { MDXClientLazy, type MDXComponents } from "../src/csr";
import { serialize } from "../src/csr/serialize.js";
import { ErrorBoundary } from "./ErrorBoundaryForTests.js";
describe("MDXClientLazy", () => {
const ErrorComponent = ({ error }: { error: Error }) => {
return <div data-testid="mdx-error">{error.message}</div>;
};
const mdxComponents = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
wrapper: (props: ComponentProps<"div"> & { components: MDXComponents }) => {
const { components, children, ...rest } = props; // eslint-disable-line @typescript-eslint/no-unused-vars
return (
<div data-testid="mdx-layout" {...rest}>
{children}
</div>
);
},
};
test("works as expected", async () => {
const mdxSource = await serialize({
source: "hi <Test name={bar} />",
options: {
scope: {
bar: "ipikuka",
},
},
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
render(
<MDXClientLazy components={mdxComponents} {...mdxSource} onError={ErrorComponent} />,
);
await waitFor(() => {
const layoutDiv = screen.queryByTestId("mdx-layout");
expect(layoutDiv?.innerHTML).toContain("<p>hi <strong>ipikuka</strong></p>");
});
});
test("works with catchable errors", async () => {
const mdxSource = await serialize({
source: "import x from 'y'",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
render(
<MDXClientLazy components={mdxComponents} {...mdxSource} onError={ErrorComponent} />,
);
const errorDiv = await screen.findByTestId("mdx-error", {}, { timeout: 2000 });
expect(errorDiv).toMatchInlineSnapshot(`
<div
data-testid="mdx-error"
>
await is only valid in async functions and the top level bodies of modules
</div>
`);
});
test("uncatchable runtime error", async () => {
const mdxSource = await serialize({
source: "hi {bar}",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const onError = vi.fn();
render(
<ErrorBoundary
fallback={<div data-testid="mdx-error">Something went wrong</div>}
onError={onError}
>
<MDXClientLazy components={mdxComponents} {...mdxSource} onError={ErrorComponent} />
</ErrorBoundary>,
);
await waitFor(() =>
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
name: "ReferenceError",
message: expect.stringContaining("bar is not defined"),
}),
expect.objectContaining({
componentStack: expect.stringContaining("_createMdxContent"),
}),
),
);
const errorDiv = await screen.findByTestId("mdx-error");
expect(errorDiv).toHaveTextContent("Something went wrong");
expect(consoleErrorSpy).toHaveBeenCalled();
consoleErrorSpy.mockRestore();
});
});
================================================
FILE: tests/test.MDXProvider.spec.tsx
================================================
import { describe, expect, test } from "vitest";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { serialize } from "../src/csr/serialize.js";
import { MDXClient, MDXProvider, type MDXComponents } from "../src/csr/index.js";
// the test cases are taken from `@mdx-js/react`for reference
describe("MDXProvider", () => {
test("should support `components` with `MDXProvider`", async () => {
const mdxSource = await serialize({
source: "# hi",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
expect(
ReactDOMServer.renderToStaticMarkup(
<MDXProvider
components={{
h1(properties) {
return <h1 style={{ color: "tomato" }} {...properties} />;
},
}}
>
<MDXClient {...mdxSource} />
</MDXProvider>,
),
'<h1 style="color:tomato">hi</h1>',
);
});
test("should support `wrapper` in `components`", async () => {
const mdxSource = await serialize({
source: "# hi",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
const CustomWrapper = (
props: React.JSX.IntrinsicElements["div"] & { components: MDXComponents },
) => {
const { components, ...rest } = props; // eslint-disable-line @typescript-eslint/no-unused-vars
return <div id="layout" {...rest} />;
};
expect(
ReactDOMServer.renderToStaticMarkup(
<MDXProvider
components={{
wrapper: CustomWrapper,
}}
>
<MDXClient {...mdxSource} />
</MDXProvider>,
),
'<div id="layout"><h1>hi</h1></div>',
);
});
test("should combine components in nested `MDXProvider`s", async () => {
const mdxSource = await serialize({
source: "# hi\n## hello",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
expect(
ReactDOMServer.renderToStaticMarkup(
<MDXProvider
components={{
h1(properties) {
return <h1 style={{ color: "tomato" }} {...properties} />;
},
h2(properties) {
return <h2 style={{ color: "rebeccapurple" }} {...properties} />;
},
}}
>
<MDXProvider
components={{
h2(properties) {
return <h2 style={{ color: "papayawhip" }} {...properties} />;
},
}}
>
<MDXClient {...mdxSource} />
</MDXProvider>
</MDXProvider>,
),
'<h1 style="color:tomato">hi</h1>\n<h2 style="color:papayawhip">hello</h2>',
);
});
test("should support components as a function", async () => {
const mdxSource = await serialize({
source: "# hi\n## hello",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
expect(
ReactDOMServer.renderToStaticMarkup(
<MDXProvider
components={{
h1(properties) {
return <h1 style={{ color: "tomato" }} {...properties} />;
},
h2(properties) {
return <h2 style={{ color: "rebeccapurple" }} {...properties} />;
},
}}
>
<MDXProvider
components={function () {
return {
h2(properties) {
return <h2 style={{ color: "papayawhip" }} {...properties} />;
},
};
}}
>
<MDXClient {...mdxSource} />
</MDXProvider>
</MDXProvider>,
),
'<h1>hi</h1>\n<h2 style="color:papayawhip">hello</h2>',
);
});
test("should support a `disableParentContext` prop (sandbox)", async () => {
const mdxSource = await serialize({
source: "# hi",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
expect(
ReactDOMServer.renderToStaticMarkup(
<MDXProvider
components={{
h1(properties) {
return <h1 style={{ color: "tomato" }} {...properties} />;
},
}}
>
<MDXClient {...mdxSource} disableParentContext />
</MDXProvider>,
),
"<h1>hi</h1>",
);
});
test("should support a `disableParentContext` *and* `components` as a function", async () => {
const mdxSource = await serialize({
source: "# hi\n## hello",
});
if ("error" in mdxSource) throw new Error("shouldn't have any MDX syntax error");
expect(
ReactDOMServer.renderToStaticMarkup(
<MDXProvider
components={{
h1(properties) {
return <h1 style={{ color: "tomato" }} {...properties} />;
},
}}
>
<MDXProvider
disableParentContext
components={function () {
return {
h2(properties) {
return <h2 style={{ color: "papayawhip" }} {...properties} />;
},
};
}}
>
<MDXClient {...mdxSource} />
</MDXProvider>
</MDXProvider>,
),
'<h1>hi</h1>\n<h2 style="color:papayawhip">hello</h2>',
);
});
});
================================================
FILE: tests/test.MDXRemote.esm.spec.tsx
================================================
import { describe, expect, test } from "vitest";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { render, screen } from "@testing-library/react";
import { MDXRemote, type MDXRemoteOptions, type MDXComponents } from "../src/rsc";
import { renderToStringFromStream } from "./utils";
describe("MDXRemote", () => {
// const LoadingComponent = () => {
// return <div data-testid="mdx-loading">loading</div>;
// };
const ErrorComponent = ({ error }: { error: Error }) => {
return <div data-testid="mdx-error">{error.message}</div>;
};
const mdxComponents = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
wrapper: (props: React.ComponentProps<"div"> & { components: MDXComponents }) => {
const { components, children, ...rest } = props; // eslint-disable-line @typescript-eslint/no-unused-vars
return (
<div data-testid="mdx-layout" {...rest}>
{children}
</div>
);
},
};
test("works (as func)", async () => {
const source = "hi <Test name={bar} />";
const options: MDXRemoteOptions = {
scope: {
bar: "ipikuka",
},
};
const content = await MDXRemote({
source,
options,
components: mdxComponents,
onError: ErrorComponent,
});
expect(ReactDOMServer.renderToStaticMarkup(content)).toMatchInlineSnapshot(
`"<div data-testid="mdx-layout"><p>hi <strong>ipikuka</strong></p></div>"`,
);
});
test("works (as jsx)", async () => {
const source = "hi <Test name={bar} />";
const options: MDXRemoteOptions = {
scope: {
bar: "ipikuka",
},
};
const element = (
<MDXRemote
source={source}
options={options}
components={mdxComponents}
onError={ErrorComponent}
/>
);
expect(await renderToStringFromStream(element)).toMatchInlineSnapshot(
`"<div data-testid="mdx-layout"><p>hi <strong>ipikuka</strong></p></div>"`,
);
});
test("works with catchable error but no Error Component (as func)", async () => {
const source = "import x from 'y'";
try {
await MDXRemote({
source,
components: mdxComponents,
});
} catch (error) {
expect(error).toMatchInlineSnapshot(
`[Error: Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`]`,
);
}
// second way
await expect(
MDXRemote({
source,
components: mdxComponents,
}),
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`]`,
);
});
test("works with catchable error but no Error Component (as jsx)", async () => {
const source = "import x from 'y'";
const element = <MDXRemote source={source} components={mdxComponents} />;
try {
await renderToStringFromStream(element);
} catch (error) {
expect(error).toMatchInlineSnapshot(
`[Error: Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`]`,
);
}
// second way
await expect(renderToStringFromStream(element)).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`]`,
);
});
test("works with catchable error, with Error component (as func)", async () => {
const source = "import x from 'y'";
const content = await MDXRemote({
source,
components: mdxComponents,
onError: ErrorComponent,
});
expect(ReactDOMServer.renderToStaticMarkup(content)).toMatchInlineSnapshot(
`"<div data-testid="mdx-error">Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`</div>"`,
);
});
test("works with catchable error, with Error component (as jsx)", async () => {
const source = "import x from 'y'";
const element = (
<MDXRemote source={source} components={mdxComponents} onError={ErrorComponent} />
);
expect(await renderToStringFromStream(element)).toMatchInlineSnapshot(
`"<div data-testid="mdx-error">Unexpected missing \`options.baseUrl\` needed to support \`export … from\`, \`import\`, or \`import.meta.url\` when generating \`function-body\`</div>"`,
);
});
test("catchable error (as func)", async () => {
const source = "import x from 'y'";
const options: MDXRemoteOptions = {
mdxOptions: {
baseUrl: import.meta.url,
},
};
const content = await MDXRemote({
source,
options,
components: mdxComponents,
onError: ErrorComponent,
});
expect(ReactDOMServer.renderToStaticMarkup(content)).toContain("Cannot find package");
expect(ReactDOMServer.renderToStaticMarkup(content)).toMatch(/Cannot find package/);
// just for testing it with @testing-library
render(content);
expect(screen.getByTestId("mdx-error")).toHaveTextContent("Cannot find package 'y'");
});
test("catchable error (as jsx)", async () => {
const source = "import x from 'y'";
const options: MDXRemoteOptions = {
mdxOptions: {
baseUrl: import.meta.url,
},
};
const element = (
<MDXRemote
source={source}
options={options}
components={mdxComponents}
onError={ErrorComponent}
/>
);
const content = await renderToStringFromStream(element);
expect(content).toContain("Cannot find package");
expect(content).toMatch(/Cannot find package/);
// just for testing it with @testing-library
render(<div dangerouslySetInnerHTML={{ __html: content }} />);
expect(screen.getByTestId("mdx-error")).toBeInTheDocument();
expect(screen.getByTestId("mdx-error")).toHaveTextContent("Cannot find package 'y'");
});
test("uncatchable error (as func)", async () => {
const source = "hi {bar}";
const content = await MDXRemote({
source,
components: mdxComponents,
onError: ErrorComponent,
});
expect(() =>
ReactDOMServer.renderToStaticMarkup(content),
).toThrowErrorMatchingInlineSnapshot(`[ReferenceError: bar is not defined]`);
});
test("uncatchable error (as jsx)", async () => {
const source = "hi {bar}";
const element = (
<MDXRemote source={source} components={mdxComponents} onError={ErrorComponent} />
);
await expect(renderToStringFromStream(element)).rejects.toThrowErrorMatchingInlineSnapshot(
`[ReferenceError: bar is not defined]`,
);
});
});
================================================
FILE: tests/test.MDXRemote.spec.tsx
================================================
import { vi, describe, test, expect } from "vitest";
import type { Plugin } from "unified";
import { VFile } from "vfile";
import dedent from "dedent";
import remarkEmoji from "remark-emoji";
import remarkFlexibleMarkers from "remark-flexible-markers";
import recmaMdxChangeProps from "recma-mdx-change-props";
import recmaMdxEscapeMissingComponents from "recma-mdx-escape-missing-components";
import { MDXRemote, type MDXRemoteOptions, type MDXComponents } from "../src/rsc";
import { compile } from "../src/lib/compile";
import { renderToStringFromStream } from "./utils";
describe("MDXRemote", () => {
test("simple", async () => {
const source = "foo **bar**";
const element = <MDXRemote source={source} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`"<p>foo <strong>bar</strong></p>"`);
});
test("with component 1", async () => {
const source = 'foo <Test name="test" />';
const element = (
<MDXRemote
source={source}
components={{
Test: ({ name }: { name: string }) => <span>hello {name}</span>,
}}
/>
);
// React inserts a <!-- --> comment in streaming SSR to separate adjacent text nodes.
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`"<p>foo <span>hello <!-- -->test</span></p>"`);
const contentStrippedComments = await renderToStringFromStream(element, {
stripReactSSRComments: true,
});
expect(contentStrippedComments).toMatchInlineSnapshot(
`"<p>foo <span>hello test</span></p>"`,
);
});
test("with component 2", async () => {
const source = 'foo <Test name="test" />';
const element = (
<MDXRemote
source={source}
components={{
Test: ({ name }: { name: string }) => <span>{`hello ${name}`}</span>,
}}
/>
);
// strpping comment is NOT needed because the text is concatenated into a single node.
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`"<p>foo <span>hello test</span></p>"`);
});
test("with some remarkPlugins in mdxOptions", async () => {
const source = "==hello :tada: Talat Kuyuk==";
const options: MDXRemoteOptions = {
mdxOptions: {
remarkPlugins: [remarkFlexibleMarkers, remarkEmoji],
},
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(
`"<p><mark class="flexible-marker flexible-marker-default">hello 🎉 Talat Kuyuk</mark></p>"`,
);
});
test("with scope", async () => {
const source = "hi {bar}";
const options: MDXRemoteOptions = {
scope: {
bar: "ipikuka",
},
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`"<p>hi ipikuka</p>"`);
});
test("with scope and component", async () => {
const source = "hi <Test name={bar} />";
const options: MDXRemoteOptions = {
scope: {
bar: "ipikuka",
},
};
const components = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
};
const element = <MDXRemote source={source} options={options} components={components} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`"<p>hi <strong>ipikuka</strong></p>"`);
});
test("with scope in which consists props key escaped with no reason", async () => {
const source = dedent`
Hi {props.bar}
<Test name={props.foo} />
`;
const options: MDXRemoteOptions = {
scope: {
props: {
bar: "barbar",
foo: "foofoo",
},
},
};
const components = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
};
const element = <MDXRemote source={source} options={options} components={components} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"<p>Hi </p>
<strong></strong>"
`);
});
test("with scope in which consists props key works as expected using a recma plugin", async () => {
const source = dedent`
Hi {props.bar}
<Test name={props.foo} />
`;
const options: MDXRemoteOptions = {
scope: {
props: {
bar: "barbar",
foo: "foofoo",
},
},
mdxOptions: {
recmaPlugins: [recmaMdxChangeProps],
},
};
const components = {
Test: ({ name }: { name: string }) => <strong>{name}</strong>,
};
const element = <MDXRemote source={source} options={options} components={components} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`
"<p>Hi barbar</p>
<strong>foofoo</strong>"
`);
});
test("with frontmatter supplying frontmatter's type argument", async () => {
const source = dedent`
---
title: 'My Article'
---
## {frontmatter.title}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"<h2>My Article</h2>"
`);
});
test("with frontmatter and scope", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title}
Hi *{name}*
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
scope: { name: "Talat Kuyuk" },
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"<h1>My Article</h1>
<p>Hi <em>Talat Kuyuk</em></p>"
`);
});
test("strips any undefined frontmatters without giving an error", async () => {
const source = dedent`
---
title: 'My Article'
---
The title is {frontmatter.title} and {frontmatter.subtitle}.
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`
"<p>The title is My Article and .</p>"
`);
});
test("supports component names with a dot(.)", async () => {
const source = "<motion.p />";
const components: MDXComponents = {
// @ts-ignore no match for the signature
motion: { p: () => <p>Hello world</p> },
};
const element = <MDXRemote source={source} components={components} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"<p>Hello world</p>"
`);
});
test("renders fragments", async () => {
const source = "<Test content={<>Renders fragments</>} />";
const components = {
Test: ({ content }: { content: string }) => <>{content}</>,
};
const element = <MDXRemote source={source} components={components} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"Renders fragments"
`);
});
test("supports VFile", async () => {
const source = new VFile("foo **bar**");
const element = <MDXRemote source={source} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"<p>foo <strong>bar</strong></p>"
`);
});
test("supports Buffer", async () => {
const source = Buffer.from("foo **bar**");
const element = <MDXRemote source={source} />;
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(`
"<p>foo <strong>bar</strong></p>"
`);
});
test("debug compiled source", async () => {
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
const result = await compile(new VFile("Hi"));
await renderToStringFromStream(
<MDXRemote source="Hi" options={{ debug: { compiledSource: true } }} />,
);
expect(logSpy).toHaveBeenCalledTimes(1);
expect(logSpy).toHaveBeenCalledWith(String(result.compiledSource));
logSpy.mockRestore(); // Restore original console.log behavior
});
});
describe("vfileDataIntoScope in MDXRemote function, no scope but vfileDataIntoScope injects data into scope", () => {
const remarkAddBarFoo: Plugin = () => (_, file) => {
file.data["bar"] = "barbar";
file.data["foo"] = "foofoo";
};
test("Throw error for missing expression in scope, no 'vfileDataIntoScope'", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title} {bar} {foo}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
mdxOptions: {
remarkPlugins: [remarkAddBarFoo],
},
};
const element = <MDXRemote source={source} options={options} />;
try {
await renderToStringFromStream(element);
} catch (error) {
// Because the first non-exist expression in scope is bar in the content
expect(error).toMatchInlineSnapshot(`[ReferenceError: bar is not defined]`);
}
});
test("Throw error for missing expression in scope, no cover 'vfileDataIntoScope' - string", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title} {bar} {foo}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
vfileDataIntoScope: "bar",
mdxOptions: {
remarkPlugins: [remarkAddBarFoo],
},
};
const element = <MDXRemote source={source} options={options} />;
try {
await renderToStringFromStream(element);
} catch (error) {
// Because, bar is in scope (thanks to vfileDataIntoScope), but foo
expect(error).toMatchInlineSnapshot(`[ReferenceError: foo is not defined]`);
}
});
test("works with the option 'vfileDataIntoScope' - string array", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title} {bar} {foo}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
vfileDataIntoScope: ["bar", "foo"],
mdxOptions: {
remarkPlugins: [remarkAddBarFoo],
},
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`"<h1>My Article barbar foofoo</h1>"`);
});
test("works with the option 'vfileDataIntoScope' - boolean true", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title} {bar} {foo}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
vfileDataIntoScope: true,
mdxOptions: {
remarkPlugins: [remarkAddBarFoo],
},
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`"<h1>My Article barbar foofoo</h1>"`);
});
test("works the option 'vfileDataIntoScope' - object", async () => {
const source = dedent`
---
title: 'My Article'
---
# {mymatter.title}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
vfileDataIntoScope: { name: "matter", as: "mymatter" },
};
// file.matter is created by `parseFrontmatter: true`
// vfileDataIntoScope injects it as `mymatter` into scope
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`"<h1>My Article</h1>"`);
});
test("works the option 'vfileDataIntoScope' - object array", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title} {newbar} {newfoo}
`;
const options: MDXRemoteOptions = {
scope: {},
parseFrontmatter: true,
vfileDataIntoScope: [
{ name: "bar", as: "newbar" },
{ name: "foo", as: "newfoo" },
],
mdxOptions: {
remarkPlugins: [remarkAddBarFoo],
},
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`"<h1>My Article barbar foofoo</h1>"`);
});
test("works the option 'vfileDataIntoScope' - mixed array", async () => {
const source = dedent`
---
title: 'My Article'
---
# {frontmatter.title} {bar} {newfoo}
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
vfileDataIntoScope: ["bar", { name: "foo", as: "newfoo" }],
mdxOptions: {
remarkPlugins: [remarkAddBarFoo],
},
};
const element = <MDXRemote source={source} options={options} />;
const content = await renderToStringFromStream(element, { stripReactSSRComments: true });
expect(content).toMatchInlineSnapshot(`"<h1>My Article barbar foofoo</h1>"`);
});
});
describe("error handling in MDXRemote", () => {
const ErrorComponent = ({ error }: { error: Error }) => {
return <div data-testid="mdx-error">{error.message}</div>;
};
test("prints helpful message from compile MDX error, no Error component", async () => {
const source = dedent`
---
title: 'My Article'
---
This is very bad syntax <GITHUB_USER>
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
};
const element = <MDXRemote source={source} options={options} />;
try {
const content = await renderToStringFromStream(element);
expect(content).toMatchInlineSnapshot(); // above render throwed error, so no content
} catch (error) {
// The error is thrown as a raw Error object (not rendered to HTML)
expect(error).toMatchInlineSnapshot(`
[Error: [next-mdx-remote-client] error compiling MDX:
Expected a closing tag for \`<GITHUB_USER>\` (1:25-1:38) before the end of \`paragraph\`
> 1 | This is very bad syntax <GITHUB_USER>
| ^
More information: https://mdxjs.com/docs/troubleshooting-mdx]
`);
}
// the second way of testing
await expect(renderToStringFromStream(element)).rejects.toMatchInlineSnapshot(`
[Error: [next-mdx-remote-client] error compiling MDX:
Expected a closing tag for \`<GITHUB_USER>\` (1:25-1:38) before the end of \`paragraph\`
> 1 | This is very bad syntax <GITHUB_USER>
| ^
More information: https://mdxjs.com/docs/troubleshooting-mdx]
`);
});
test("prints helpful message from compile MDX error, with Error component", async () => {
// This test shows that MDX syntax errors are catched by `next-mdx-remote-client`
const source = dedent`
---
title: 'My Article'
---
This is very bad syntax <GITHUB_USER>
`;
const options: MDXRemoteOptions = {
parseFrontmatter: true,
};
const element = <MDXRemote source={source} options={options} onError={ErrorComponent} />;
const content = await renderToStringFromStream(element);
// The error is rendered inside a React component (ErrorComponent) and thus HTML-escaped by React
expect(content).toMatchInlineSnapshot(`
"<div data-testid="mdx-error">[next-mdx-remote-client] error compiling MDX:
Expected a closing tag for \`<GITHUB_USER>\` (1:25-1:38) before the end of \`paragraph\`
> 1 | This is very bad syntax <GITHUB_USER>
| ^
More information: https://mdxjs.com/docs/troubleshooting-mdx</div>"
`);
});
test("missing a scope value causes runtime error during render, no Error component", async () => {
const source = "hi {bar}";
const element = <MDXRemote source={source} />;
try {
const content = await renderToStringFromStream(element); // the render throws an error
expect(content).toMatchInlineSnapshot(); // so no content
} catch (error) {
expect(error).toMatchInlineSnapshot(`[ReferenceError: bar is not defined]`);
}
// the second way of testing
await expect(renderToStringFromStream(element)).rejects.toThrowErrorMatchingInlineSnapshot(
`[ReferenceError: bar is not defined]`,
);
});
test("missing a scope value causes runtime error during render, with Error component", async () => {
// This test shows that a runtime error can not be catched by `next-mdx-remote-client`
const source = "hi {bar}";
const element = <MDXRemote source={source} onError={ErrorComponent} />;
try {
const content = await renderToStringFromStream(element); // the render throws an error
expect(content).toMatchInlineSnapshot(); // so no content
} catch (error) {
expect(error).toMatchInlineSnapshot(`[ReferenceError: bar is not defined]`);
}
// the second way of testing
await expect(renderToStringFromStream(element)).rejects.toThrowErrorMatchingInlineSnapshot(
`[ReferenceError: bar is not defined]`,
);
});
test("missing a component causes runtime error during render, no Error component", async () => {
const source = "hi <Test />";
const element = <MDXRemote source={source} />;
try {
const content = await renderToStringFromStream(element); // the render throws an error
expect(content).toMatchInlineSnapshot(); // so no content
} catch (error) {
expect(error).toMatchInlineSnapshot(
`[Error: Expected component \`Test\` to be defined: you likely forgot to import, pass, or provide it.]`,
);
}
// the second way of testing
await expect(renderToStringFromStream(element)).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Expected component \`Test\` to be defined: you likely forgot to import, pass, or provide it.]`,
);
});
test("missing a component causes runtime error during render, with Error component", async () => {
// This test shows that a runtime error can not be catched by `next-mdx-remote-client`
const source = "hi <Test />";
const element = <MDXRemote source={source} onError={ErrorComponent} />;
try {
const content = await renderToStringFromStream(element); // the render throws an error
expect(content).toMatchInlineSnapshot(); // so no content
} catch (error) {
expect(error).toMatchInlineSnapshot(
`[Error: Expected component \`Test\` to be defined: you likely forgot to import, pass, or provide it.]`,
);
}
// the second way of testing
await expect(renderToStringFromStream(element)).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Expected component \`Test\` to be defined: you likely forgot to import, pass, or provide it.]`,
);
});
test("missing components can be escaped via a recma plugin without giving runtime error", async () => {
const source = "hi <Test />";
const element =
gitextract_yhdnptxl/ ├── .editorconfig ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ ├── main.yml │ └── publish.yml ├── .gitignore ├── .npmignore ├── .npmrc ├── .prettierignore ├── .prettierrc.json ├── LICENSE ├── README.md ├── codecov.yml ├── eslint.config.js ├── migration_guide.md ├── package.json ├── src/ │ ├── csr/ │ │ ├── MDXClient.tsx │ │ ├── MDXClientAsync.tsx │ │ ├── MDXClientLazy.tsx │ │ ├── hydrate.tsx │ │ ├── hydrateAsync.tsx │ │ ├── hydrateLazy.tsx │ │ ├── idle-callback-polyfill.js │ │ ├── index.ts │ │ ├── requestIdleCallback.d.ts │ │ ├── serialize.ts │ │ └── types.ts │ ├── lib/ │ │ ├── compile.ts │ │ ├── prepare.ts │ │ ├── run.ts │ │ ├── types.ts │ │ └── util.ts │ ├── rsc/ │ │ ├── MDXRemote.tsx │ │ ├── evaluate.tsx │ │ ├── index.ts │ │ └── types.ts │ └── utils/ │ ├── getFrontmatter.ts │ └── index.ts ├── tests/ │ ├── ErrorBoundaryClassic.jsx │ ├── ErrorBoundaryForTests.tsx │ ├── context/ │ │ ├── ExampleForm.mjs │ │ ├── ExampleFormTransformedAutomatic.mjs │ │ ├── ExampleFormTransformedClassic.mjs │ │ ├── HelloDave.mjs │ │ ├── components.js │ │ └── data.js │ ├── test.MDXClient.spec.tsx │ ├── test.MDXClientAsync.esm.spec.tsx │ ├── test.MDXClientLazy.spec.tsx │ ├── test.MDXProvider.spec.tsx │ ├── test.MDXRemote.esm.spec.tsx │ ├── test.MDXRemote.spec.tsx │ ├── test.compile.spec.tsx │ ├── test.core.spec.ts │ ├── test.evaluate.esm.spec.tsx │ ├── test.evaluate.spec.tsx │ ├── test.original.compile.spec.tsx │ ├── test.run.spec.tsx │ ├── test.serialize-hydrate.spec.tsx │ ├── test.utils.spec.ts │ ├── test.wrapper.spec.tsx │ └── utils/ │ └── index.ts ├── tsconfig.json ├── vite.config.js └── vitest-setup-tests.js
SYMBOL INDEX (93 symbols across 34 files)
FILE: src/csr/MDXClient.tsx
function MDXClient (line 12) | function MDXClient(props: MDXClientProps): React.JSX.Element {
FILE: src/csr/MDXClientAsync.tsx
function MDXClientAsync (line 16) | function MDXClientAsync(props: MDXClientAsyncProps): React.JSX.Element {
FILE: src/csr/MDXClientLazy.tsx
function MDXClientLazy (line 14) | function MDXClientLazy(props: MDXClientProps): React.JSX.Element {
FILE: src/csr/hydrate.tsx
function hydrate (line 17) | function hydrate({
FILE: src/csr/hydrateAsync.tsx
function hydrateAsync (line 23) | function hydrateAsync({
FILE: src/csr/hydrateLazy.tsx
function hydrateLazy (line 21) | function hydrateLazy({
FILE: src/csr/requestIdleCallback.d.ts
type RequestIdleCallbackHandle (line 9) | type RequestIdleCallbackHandle = number;
type RequestIdleCallbackOptions (line 11) | type RequestIdleCallbackOptions = {
type RequestIdleCallbackDeadline (line 15) | type RequestIdleCallbackDeadline = {
type Window (line 21) | interface Window {
FILE: src/csr/serialize.ts
function serialize (line 23) | async function serialize<
FILE: src/csr/types.ts
type Prettify (line 15) | type Prettify<T> = { [K in keyof T]: T[K] } & {};
type SerializeProps (line 17) | type SerializeProps<TScope extends Record<string, unknown> = Record<stri...
type SerializeOptions (line 28) | type SerializeOptions<TScope extends Record<string, unknown> = Record<st...
type SerializeMdxOptions (line 63) | type SerializeMdxOptions = Omit<
type SerializeResult (line 68) | type SerializeResult<
type HydrateProps (line 100) | type HydrateProps = {
type HydrateResult (line 128) | type HydrateResult = {
type MDXClientProps (line 143) | type MDXClientProps = Prettify<
type HydrateAsyncProps (line 149) | type HydrateAsyncProps = Prettify<
type HydrateAsyncOptions (line 162) | type HydrateAsyncOptions = {
type MDXClientAsyncProps (line 169) | type MDXClientAsyncProps = Prettify<
type MDXClientAsyncOptions (line 175) | type MDXClientAsyncOptions = HydrateAsyncOptions;
FILE: src/lib/compile.ts
function composeCompileOptions (line 20) | function composeCompileOptions(options: CompileOptions = {}): CompileMDX...
function compile (line 42) | async function compile(vfile: VFile, options?: CompileOptions): Promise<...
FILE: src/lib/prepare.ts
function prepare (line 18) | function prepare<TFrontmatter extends Record<string, unknown> = Record<s...
function looksLikeAVFile (line 38) | function looksLikeAVFile(value?: Compatible): value is VFile {
FILE: src/lib/run.ts
type JsxRuntime (line 14) | type JsxRuntime = {
type JsxDevRuntime (line 20) | type JsxDevRuntime = {
function prepareConstruction (line 33) | function prepareConstruction(options: RunOptions) {
function runSync (line 57) | function runSync(compiledSource: string, options: RunOptions): RunResult {
function runAsync (line 77) | async function runAsync(
FILE: src/lib/types.ts
type PrepareProps (line 13) | type PrepareProps = {
type PrepareResult (line 24) | type PrepareResult<TFrontmatter = Record<string, unknown>> = {
type CompileOptions (line 35) | type CompileOptions = {
type CompileMdxOptions (line 55) | type CompileMdxOptions = Omit<OriginalCompileOptions, "outputFormat">;
type RunOptions (line 57) | type RunOptions = {
type RunMdxOptions (line 73) | type RunMdxOptions = Omit<OriginalRunOptions, "Fragment" | "jsx" | "jsxD...
type CompileResult (line 75) | type CompileResult = {
type RunResult (line 82) | type RunResult = {
FILE: src/lib/util.ts
function parsePositionInformationFromErrorMessage (line 18) | function parsePositionInformationFromErrorMessage(message: string): Sour...
function createFormattedMDXError (line 45) | function createFormattedMDXError(error: Error, source: string): Error {
type VfileDataIntoScope (line 73) | type VfileDataIntoScope =
function passVfileDataIntoScope (line 87) | function passVfileDataIntoScope(
FILE: src/rsc/MDXRemote.tsx
function MDXRemote (line 12) | async function MDXRemote(props: MDXRemoteProps): Promise<React.JSX.Eleme...
FILE: src/rsc/evaluate.tsx
function evaluate (line 19) | async function evaluate<
FILE: src/rsc/types.ts
type Prettify (line 12) | type Prettify<T> = { [K in keyof T]: T[K] } & {};
type EvaluateProps (line 14) | type EvaluateProps<TScope extends Record<string, unknown> = Record<strin...
type EvaluateOptions (line 32) | type EvaluateOptions<TScope extends Record<string, unknown> = Record<str...
type EvaluateMdxOptions (line 73) | type EvaluateMdxOptions = Omit<
type EvaluateResult (line 84) | type EvaluateResult<
type MDXRemoteProps (line 112) | type MDXRemoteProps = Prettify<
type MDXRemoteOptions (line 118) | type MDXRemoteOptions = EvaluateOptions;
FILE: src/utils/getFrontmatter.ts
function getFrontmatter (line 15) | function getFrontmatter<TFrontmatter extends Record<string, unknown>>(
FILE: tests/ErrorBoundaryClassic.jsx
class ErrorBoundary (line 3) | class ErrorBoundary extends React.Component {
method constructor (line 4) | constructor(props) {
method getDerivedStateFromError (line 12) | static getDerivedStateFromError(error) {
method componentDidCatch (line 18) | componentDidCatch(error, errorInfo) {
method render (line 22) | render() {
FILE: tests/ErrorBoundaryForTests.tsx
type ErrorBoundaryProps (line 3) | interface ErrorBoundaryProps {
type ErrorBoundaryState (line 9) | interface ErrorBoundaryState {
class ErrorBoundary (line 18) | class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBou...
method constructor (line 19) | constructor(props: ErrorBoundaryProps) {
method getDerivedStateFromError (line 24) | static getDerivedStateFromError(error: Error): ErrorBoundaryState {
method componentDidCatch (line 28) | componentDidCatch(error: Error, info: React.ErrorInfo) {
method render (line 32) | render() {
FILE: tests/context/ExampleForm.mjs
function ExampleForm (line 3) | function ExampleForm() {
FILE: tests/context/ExampleFormTransformedAutomatic.mjs
function ExampleForm (line 3) | function ExampleForm() {
FILE: tests/context/ExampleFormTransformedClassic.mjs
function ExampleForm (line 2) | function ExampleForm() {
FILE: tests/context/HelloDave.mjs
function HelloDave (line 3) | function HelloDave({ runtimeProps, ...props }) {
FILE: tests/context/components.js
function Pill (line 11) | function Pill(props) {
function Layout (line 21) | function Layout(props) {
FILE: tests/test.MDXProvider.spec.tsx
method h1 (line 22) | h1(properties) {
method h1 (line 73) | h1(properties) {
method h2 (line 76) | h2(properties) {
method h2 (line 83) | h2(properties) {
method h1 (line 107) | h1(properties) {
method h2 (line 110) | h2(properties) {
method h2 (line 118) | h2(properties) {
method h1 (line 143) | h1(properties) {
method h1 (line 166) | h1(properties) {
method h2 (line 175) | h2(properties) {
FILE: tests/test.compile.spec.tsx
type Frontmatter (line 8) | type Frontmatter = { title: string };
FILE: tests/test.evaluate.esm.spec.tsx
type Frontmatter (line 9) | type Frontmatter = { title: string };
FILE: tests/test.evaluate.spec.tsx
type Frontmatter (line 14) | type Frontmatter = { title: string };
FILE: tests/test.run.spec.tsx
function runSync_ (line 12) | function runSync_(
FILE: tests/test.serialize-hydrate.spec.tsx
type Frontmatter (line 14) | type Frontmatter = { title: string };
FILE: tests/test.utils.spec.ts
type Frontmatter (line 10) | type Frontmatter = { title: string };
FILE: tests/test.wrapper.spec.tsx
method wrapper (line 26) | wrapper(props: React.ComponentProps<"div"> & { components: MDXComponents...
method wrapper (line 42) | wrapper(props: React.ComponentProps<"div"> & { components: MDXComponents...
method wrapper (line 58) | wrapper() {
FILE: tests/utils/index.ts
type RenderOptions (line 5) | type RenderOptions = {
function renderToStringFromStream (line 14) | async function renderToStringFromStream(
Condensed preview — 64 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (305K chars).
[
{
"path": ".editorconfig",
"chars": 384,
"preview": "# Stop the editor from looking for .editorconfig files in the parent directories\nroot = true\n\n[*]\n# Non-configurable Pre"
},
{
"path": ".github/FUNDING.yml",
"chars": 18,
"preview": "github: [ipikuka]\n"
},
{
"path": ".github/workflows/main.yml",
"chars": 1198,
"preview": "name: main\non:\n pull_request:\n branches:\n - \"**\"\n push:\n branches:\n - \"**\"\njobs:\n test:\n name: Tes"
},
{
"path": ".github/workflows/publish.yml",
"chars": 592,
"preview": "name: publish to npm\non:\n release:\n types: [published]\njobs:\n publish:\n runs-on: ubuntu-latest\n permissions:\n"
},
{
"path": ".gitignore",
"chars": 52,
"preview": ".DS_Store\n.vscode\ndist\nnode_modules\narchive\ncoverage"
},
{
"path": ".npmignore",
"chars": 18,
"preview": "dist/*.tsbuildinfo"
},
{
"path": ".npmrc",
"chars": 19,
"preview": "ignore-scripts=true"
},
{
"path": ".prettierignore",
"chars": 99,
"preview": ".DS_Store\n.vscode\ndist\nnode_modules\npackage-lock.json\narchive\ncoverage\nREADME.md\nmigration_guide.md"
},
{
"path": ".prettierrc.json",
"chars": 228,
"preview": "{\n \"singleQuote\": false,\n \"bracketSpacing\": true,\n \"trailingComma\": \"all\",\n \"tabWidth\": 2,\n \"useTabs\": false,\n \"se"
},
{
"path": "LICENSE",
"chars": 15646,
"preview": "# Mozilla Public License Version 2.0\n\nCopyright (c) 2026 @talatkuyuk AKA @ipikuka\n\n1. Definitions\n\n---\n\n1.1. \"Contributo"
},
{
"path": "README.md",
"chars": 63387,
"preview": "**A robust Next.js newsletter `Next.js Weekly` is sponsoring me** 💖\n["
},
{
"path": "codecov.yml",
"chars": 69,
"preview": "coverage:\n status:\n project:\n default:\n target: 100%\n"
},
{
"path": "eslint.config.js",
"chars": 1592,
"preview": "import { defineConfig } from \"eslint/config\";\nimport eslint from \"@eslint/js\";\nimport tseslint from \"typescript-eslint\";"
},
{
"path": "migration_guide.md",
"chars": 21181,
"preview": "# Migration guide from `next-mdx-remote`\n\n## Migration examples for \"pages\" router\n\nAll examples have been taken from **"
},
{
"path": "package.json",
"chars": 3898,
"preview": "{\n \"name\": \"next-mdx-remote-client\",\n \"description\": \"A wrapper of the `@mdx-js/mdx` for the `nextjs` applications in "
},
{
"path": "src/csr/MDXClient.tsx",
"chars": 589,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport type { MDXClientProps } fr"
},
{
"path": "src/csr/MDXClientAsync.tsx",
"chars": 752,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport type { MDXClientAsyncProps"
},
{
"path": "src/csr/MDXClientLazy.tsx",
"chars": 684,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport type { MDXClientProps } fr"
},
{
"path": "src/csr/hydrate.tsx",
"chars": 1340,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { MDXProvider, useMDXCompo"
},
{
"path": "src/csr/hydrateAsync.tsx",
"chars": 2289,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { useEffect, useState } fr"
},
{
"path": "src/csr/hydrateLazy.tsx",
"chars": 2380,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { useEffect, useMemo, useS"
},
{
"path": "src/csr/idle-callback-polyfill.js",
"chars": 579,
"preview": "/**\n * Copyright (c) HashiCorp, Inc.\n * SPDX-License-Identifier: MPL-2.0\n *\n * reference to https://github.com/hashicorp"
},
{
"path": "src/csr/index.ts",
"chars": 879,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nexport { hydrate } from \"./hydrat"
},
{
"path": "src/csr/requestIdleCallback.d.ts",
"chars": 748,
"preview": "/**\n * Copyright (c) HashiCorp, Inc.\n * SPDX-License-Identifier: MPL-2.0\n *\n * reference to https://github.com/hashicorp"
},
{
"path": "src/csr/serialize.ts",
"chars": 1857,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { serializeError } from \"s"
},
{
"path": "src/csr/types.ts",
"chars": 5116,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport type {\n CompileOptions as"
},
{
"path": "src/lib/compile.ts",
"chars": 1682,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { compile as compileMDX, t"
},
{
"path": "src/lib/prepare.ts",
"chars": 1230,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { type Compatible, VFile }"
},
{
"path": "src/lib/run.ts",
"chars": 2682,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport * as React from \"react\";\ni"
},
{
"path": "src/lib/types.ts",
"chars": 2536,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport type {\n CompileOptions as"
},
{
"path": "src/lib/util.ts",
"chars": 3844,
"preview": "/**\n * Copyright (c) HashiCorp, Inc.\n * SPDX-License-Identifier: MPL-2.0\n *\n * reference to https://github.com/hashicorp"
},
{
"path": "src/rsc/MDXRemote.tsx",
"chars": 622,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { evaluate } from \"./evalu"
},
{
"path": "src/rsc/evaluate.tsx",
"chars": 2208,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { compile } from \"../lib/c"
},
{
"path": "src/rsc/index.ts",
"chars": 447,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nexport { MDXRemote } from \"./MDXR"
},
{
"path": "src/rsc/types.ts",
"chars": 3538,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport type { EvaluateOptions as "
},
{
"path": "src/utils/getFrontmatter.ts",
"chars": 797,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\nimport { type Compatible, VFile }"
},
{
"path": "src/utils/index.ts",
"chars": 210,
"preview": "/**\n * Copyright (c) @talatkuyuk AKA @ipikuka\n * SPDX-License-Identifier: MPL-2.0\n */\n\n// for who needs to parse and get"
},
{
"path": "tests/ErrorBoundaryClassic.jsx",
"chars": 982,
"preview": "import React from \"react\";\n\nclass ErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n\n "
},
{
"path": "tests/ErrorBoundaryForTests.tsx",
"chars": 988,
"preview": "import React from \"react\";\n\ninterface ErrorBoundaryProps {\n fallback: React.ReactNode;\n onError?: (error: Error, info:"
},
{
"path": "tests/context/ExampleForm.mjs",
"chars": 465,
"preview": "import { useId, useState } from \"react\";\n\nfunction ExampleForm() {\n const id = useId(); // Generates a unique ID\n cons"
},
{
"path": "tests/context/ExampleFormTransformedAutomatic.mjs",
"chars": 693,
"preview": "import { useId, useState } from \"react\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nfunction Exampl"
},
{
"path": "tests/context/ExampleFormTransformedClassic.mjs",
"chars": 649,
"preview": "import React, { useId, useState } from \"react\";\nfunction ExampleForm() {\n const id = useId(); // Generates a unique ID\n"
},
{
"path": "tests/context/HelloDave.mjs",
"chars": 356,
"preview": "import * as ReactModule from \"react\";\n\nexport default function HelloDave({ runtimeProps, ...props }) {\n const { React ="
},
{
"path": "tests/context/components.js",
"chars": 579,
"preview": "// the same test file taken from @mdx-js/mdx test files iot be inline with\n\nimport React from \"react\";\n\n/**\n * @param {R"
},
{
"path": "tests/context/data.js",
"chars": 276,
"preview": "// the same test file taken from @mdx-js/mdx test files iot be inline with\n\n/**\n * Number.\n */\nexport const number = 3.1"
},
{
"path": "tests/test.MDXClient.spec.tsx",
"chars": 2714,
"preview": "import { describe, expect, test } from \"vitest\";\n\nimport ReactDOMServer from \"react-dom/server\";\n\nimport { MDXClient } f"
},
{
"path": "tests/test.MDXClientAsync.esm.spec.tsx",
"chars": 4963,
"preview": "import { vi, describe, expect, test } from \"vitest\";\n\nimport type { ComponentProps } from \"react\";\nimport { render, scre"
},
{
"path": "tests/test.MDXClientLazy.spec.tsx",
"chars": 3301,
"preview": "import { vi, describe, expect, test } from \"vitest\";\n\nimport type { ComponentProps } from \"react\";\nimport { render, scre"
},
{
"path": "tests/test.MDXProvider.spec.tsx",
"chars": 5358,
"preview": "import { describe, expect, test } from \"vitest\";\n\nimport React from \"react\";\nimport ReactDOMServer from \"react-dom/serve"
},
{
"path": "tests/test.MDXRemote.esm.spec.tsx",
"chars": 6924,
"preview": "import { describe, expect, test } from \"vitest\";\n\nimport React from \"react\";\nimport ReactDOMServer from \"react-dom/serve"
},
{
"path": "tests/test.MDXRemote.spec.tsx",
"chars": 20101,
"preview": "import { vi, describe, test, expect } from \"vitest\";\n\nimport type { Plugin } from \"unified\";\nimport { VFile } from \"vfil"
},
{
"path": "tests/test.compile.spec.tsx",
"chars": 13917,
"preview": "import { describe, test, expect } from \"vitest\";\n\nimport dedent from \"dedent\";\n\nimport { compile } from \"../src/lib/comp"
},
{
"path": "tests/test.core.spec.ts",
"chars": 652,
"preview": "import { test } from \"vitest\";\n\nimport assert from \"node:assert/strict\";\n\ntest(\"should expose the public apis\", async fu"
},
{
"path": "tests/test.evaluate.esm.spec.tsx",
"chars": 15169,
"preview": "import { describe, test, expect } from \"vitest\";\n\nimport ReactDOMServer from \"react-dom/server\";\nimport recmaMdxImportRe"
},
{
"path": "tests/test.evaluate.spec.tsx",
"chars": 17992,
"preview": "import { vi, describe, test, expect } from \"vitest\";\n\nimport ReactDOMServer from \"react-dom/server\";\nimport { VFile } fr"
},
{
"path": "tests/test.original.compile.spec.tsx",
"chars": 5333,
"preview": "import { test, expect } from \"vitest\";\n\nimport { compile } from \"@mdx-js/mdx\";\nimport dedent from \"dedent\";\n\ntest(\"provi"
},
{
"path": "tests/test.run.spec.tsx",
"chars": 4944,
"preview": "import { describe, test, expect } from \"vitest\";\n\nimport { VFile } from \"vfile\";\nimport dedent from \"dedent\";\n\nimport { "
},
{
"path": "tests/test.serialize-hydrate.spec.tsx",
"chars": 25082,
"preview": "import { describe, test, expect } from \"vitest\";\n\nimport ReactDOMServer from \"react-dom/server\";\nimport { VFile } from \""
},
{
"path": "tests/test.utils.spec.ts",
"chars": 5889,
"preview": "import { describe, test, expect } from \"vitest\";\n\nimport type { SourceLocation } from \"@babel/code-frame\";\nimport dedent"
},
{
"path": "tests/test.wrapper.spec.tsx",
"chars": 2212,
"preview": "import { describe, test, expect } from \"vitest\";\n\nimport React from \"react\";\nimport ReactDOMServer from \"react-dom/serve"
},
{
"path": "tests/utils/index.ts",
"chars": 1315,
"preview": "import { act, type ReactElement } from \"react\";\nimport reactDom from \"react-dom/server\";\nimport { PassThrough } from \"st"
},
{
"path": "tsconfig.json",
"chars": 469,
"preview": "{\n \"compilerOptions\": {\n \"lib\": [\"ESNext\", \"DOM\"],\n \"target\": \"ESNext\",\n \"module\": \"ESNext\",\n \"moduleResolu"
},
{
"path": "vite.config.js",
"chars": 931,
"preview": "import { defineConfig } from \"vite\";\nimport { coverageConfigDefaults } from \"vitest/config\";\nimport react from \"@vitejs/"
},
{
"path": "vitest-setup-tests.js",
"chars": 166,
"preview": "import \"@testing-library/jest-dom/vitest\";\n\nimport { afterEach } from \"vitest\";\nimport { cleanup } from \"@testing-librar"
}
]
About this extraction
This page contains the full source code of the ipikuka/next-mdx-remote-client GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 64 files (281.1 KB), approximately 73.7k tokens, and a symbol index with 93 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.