### Develop Example Docs Locally
Source: https://github.com/shuding/nextra/blob/main/README.md
Starts the 'example-docs' project locally for development. Changes will be re-rendered instantly. For core or theme package updates, a rebuild might be necessary, or use watch mode.
```bash
pnpm --filter example-docs dev
```
--------------------------------
### Install typesense-nextra-adapter
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/search/typesense/page.mdx
Install the adapter package using npm or yarn.
```sh
npm i typesense-nextra-adapter
```
--------------------------------
### Install Nextra blog theme
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/blog/index.mdx
Install the specific theme package for the blog layout.
```sh
npm i nextra-theme-blog
```
--------------------------------
### Install Next.js, Nextra, and React
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/docs/index.mdx
Use this command to install the core Next.js, Nextra, and React packages. This is the first step in setting up your project.
```sh
npm i react react-dom next nextra
```
--------------------------------
### Install Nextra Blog Theme Dependencies
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/blog-theme/start/page.mdx
Install Next.js, React, Nextra, and the Nextra Blog Theme. If Next.js is already installed, only install 'nextra' and 'nextra-theme-blog'.
```sh
npm i next react react-dom nextra nextra-theme-blog
```
--------------------------------
### Install KaTeX Package
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/advanced/latex/page.mdx
Install the `katex` package using npm or yarn if you plan to import its CSS directly.
```bash
npm i katex
```
--------------------------------
### Install Nextra dependencies
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/blog/index.mdx
Install the required packages for Next.js, Nextra, and React.
```sh
npm i next nextra react react-dom
```
--------------------------------
### Create Posts Page with Nextra
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/blog-theme/posts/page.mdx
This example shows the basic structure for a posts page in a Nextra application. It utilizes a custom `ExampleCode` component to render blog examples.
```jsx
import { ExampleCode } from 'components/example-code'
```
--------------------------------
### Install Nextra Docs Theme
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/docs/index.mdx
Install the specific theme package for documentation websites using Nextra.
```sh
npm i nextra-theme-docs
```
--------------------------------
### Import Icons and OverviewPage Component
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/page.mdx
Imports necessary icons and the OverviewPage component from local components and nextra. This setup is required for rendering the guide's overview page.
```javascript
import {
BrushIcon,
GlobeIcon,
LightningIcon,
PictureIcon,
StarsIcon
} from '@components/icons'
import { InformationCircleIcon, LinkIcon, MarkdownIcon } from 'nextra/icons'
import { OverviewPage } from '../../_components/overview-page'
```
--------------------------------
### Setup application entry point
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/blog/index.mdx
Import the theme stylesheet and configure the custom App component in pages/_app.js.
```jsx
import 'nextra-theme-blog/style.css'
export default function Nextra({ Component, pageProps }) {
const getLayout = Component.getLayout || (page => page)
return
}
```
--------------------------------
### Start the development server
Source: https://github.com/shuding/nextra/blob/main/docs/components/ready-to-go.mdx
Executes the development script defined in the project's package.json file.
```sh
npm run dev
```
```sh
yarn dev
```
```sh
pnpm dev
```
```sh
bun dev
```
--------------------------------
### Install ESLint Plugin
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/foo.md
Installs the @graphql-eslint/eslint-plugin package using npm or yarn.
```sh
npm i @graphql-eslint/eslint-plugin
```
--------------------------------
### Install Nextra dependencies
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/docs-theme/start/page.mdx
Run this command in your project directory to install the required packages for a new Nextra Docs site.
```sh
npm i next react react-dom nextra nextra-theme-docs
```
```yarn
yarn add next react react-dom nextra nextra-theme-docs
```
```pnpm
pnpm add next react react-dom nextra nextra-theme-docs
```
```bun
bun add next react react-dom nextra nextra-theme-docs
```
--------------------------------
### MathJax Example Component
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/advanced/latex/page.mdx
An example of how to programmatically compile and render MathJax content using MDXRemote.
```jsx
export async function MathJaxExample() {
const rawMdx = `~~~math
\\int_2^3x^3\\,\\mathrm{d}x
~~~`
const rawJs = await compileMdx(rawMdx, {
latex: {
renderer: 'mathjax',
options: {
config: {
tex: {
macros: {
RR: '\\mathbb{R}'
}
}
}
}
}
})
return (
)
}
```
--------------------------------
### Install Inkeep Component Library
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/search/ai/page.mdx
Install the required React component library for Inkeep.
```bash
npm i @inkeep/cxkit-react
```
--------------------------------
### Install Pagefind dependency
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/search/page.mdx
Add Pagefind as a development dependency to your project.
```sh
npm i -D pagefind
```
--------------------------------
### Global SWRConfig Setup
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/advanced/react-native.mdx
Wrap the application with SWRConfig to apply global configurations.
```jsx
```
--------------------------------
### Run development and production servers
Source: https://github.com/shuding/nextra/blob/main/docs/components/install-nextra-theme.mdx
Commands to start the application in development or production modes.
```sh
npm run dev
```
```sh
npm run build
npm run start
```
--------------------------------
### Install Dependencies with npm/yarn
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/getting-started.mdx
Installs the swr package and a special __esModule variable. Use npm2yarn to convert between npm and yarn commands.
```sh
npm i swr __esModule
```
--------------------------------
### React Bleed Component Examples
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/docs/bleed.mdx
Shows how to use the Bleed component in a React application, including examples with images and iframes. Requires importing the component.
```jsx
import { Bleed } from 'nextra/components'
Hey, I can use **Markdown** syntax here.

```
--------------------------------
### Syntax Highlighting
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/features/mdx.mdx
Examples of standard and line-highlighted code blocks in MDX.
```mdx
```js
console.log('hello, world')
```
```
```mdx
```jsx {4,6-8}
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return
failed to load
if (!data) return
loading...
return
hello {data.name}!
}
```
```jsx
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return
failed to load
if (!data) return
loading...
return
hello {data.name}!
}
```
--------------------------------
### FileTree Component Example
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/file-conventions/src-directory/page.mdx
Demonstrates the structure of a Nextra project with and without the `src` directory using the `FileTree` component.
```jsx
import { FileTree } from 'nextra/components'
export const nextConfigPackageJson = (
<>
>
)
export const folders = (
<>
>
)
**Without `src` directory**
{folders}
{nextConfigPackageJson}
**With `src` directory**
{folders}
{nextConfigPackageJson}
```
--------------------------------
### MDX Page Example (`[[...mdxPath]]/page.jsx`)
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/file-conventions/content-directory/page.mdx
This is the gateway file for the `content` directory, handling dynamic routing for MDX files. It compiles and renders MDX content.
```jsx
import fs from 'node:fs/promises'
import { compileMdx } from 'nextra/compile'
import { FileTree, Steps } from 'nextra/components'
import { MDXRemote } from 'nextra/mdx-remote'
export async function MDXPathPage() {
const filename = '[[...mdxPath]]/page.jsx'
const rawMdx = `~~~jsx filename="${filename}" showLineNumbers
${(await fs.readFile(`../examples/docs/src/app/docs/${filename}`, 'utf8')).trimEnd()}
~~~`
const rawJs = await compileMdx(rawMdx, { defaultShowCopyCode: true })
return
}
```
--------------------------------
### Index Based Paginated API Implementation
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/pagination.mdx
Example of using useSWRInfinite with an index-based API.
```jsx
const getKey = (pageIndex, previousPageData) => {
if (previousPageData && !previousPageData.length) return null // reached the end
return `/users?page=${pageIndex}&limit=10` // SWR key
}
function App() {
const { data, size, setSize } = useSWRInfinite(getKey, fetcher)
if (!data) return 'loading'
// We can now calculate the number of all users
let totalUsers = 0
for (let i = 0; i < data.length; i++) {
totalUsers += data[i].length
}
return (
{totalUsers} users listed
{data.map(users => {
// `data` is an array of each page's API response.
return users.map(user =>
{user.name}
)
})}
)
}
```
--------------------------------
### Configure Layout Component Props
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/docs-theme/built-ins/layout/page.mdx
Example of how to configure the Layout component with sidebar and docs repository props.
```jsx
import { Layout } from 'nextra-theme-docs'
export default function MyLayout({ children, ...props }) {
return (
{children}
)
}
```
--------------------------------
### CSS Example
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/getting-started.mdx
Basic CSS styling for an HTML element.
```css
html {
background: red;
}
```
--------------------------------
### Install TypeScript Dependencies
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/advanced/typescript/page.mdx
Install TypeScript and necessary type packages as dev dependencies using npm or yarn.
```sh
npm i -D typescript @types/react @types/node
```
--------------------------------
### File Tree Structure Example 1
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/getting-started.mdx
Represents a nested file structure with two main service folders, each containing a schema.graphql file.
```jsx
```
--------------------------------
### Data Fetching with Unfetch
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/data-fetching.mdx
Example of using the unfetch library for data fetching with SWR. Ensure unfetch is imported if not using Next.js.
```javascript
import fetch from 'unfetch'
const fetcher = url => fetch(url).then(r => r.json())
function App() {
const { data, error } = useSWR('/api/data', fetcher)
// ...
}
```
--------------------------------
### Tabs Component Example
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/themes/docs/tabs.mdx
Demonstrates the usage of the Tabs component with different programming languages. Use this to create multi-language code examples within your documentation.
```jsx
import { Tabs } from 'nextra/components'
```js filename="hi.js"
import { useState, useEffect } from 'react';
```
```cpp filename="hi.cpp"
#include
```
```c filename="hi.c"
#include
```
```python filename="hello.py"
print('Hello, world!')
```
```
--------------------------------
### Configure `contentDirBasePath` in `next.config.mjs`
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/file-conventions/content-directory/page.mdx
Optionally set a base path for serving content if it's not at the root. This example shows how to set it to '/docs'.
```js
import nextra from 'nextra'
const withNextra = nextra({
contentDirBasePath: '/docs' // Or even nested e.g. `/docs/advanced`
})
```
--------------------------------
### Implement Request Logger Middleware
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/middleware.mdx
A practical example of middleware that wraps the fetcher to log requests.
```jsx
function logger(useSWRNext) {
return (key, fetcher, config) => {
// Add logger to the original fetcher.
const extendedFetcher = (...args) => {
console.log('SWR Request:', key)
return fetcher(...args)
}
// Execute the hook with the new fetcher.
return useSWRNext(key, extendedFetcher, config)
}
}
// ... inside your component
useSWR(key, fetcher, { use: [logger] })
```
```plaintext
SWR Request: /api/user1
SWR Request: /api/user2
```
--------------------------------
### Configure next.config.js with plugins
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/turbopack/page.mdx
Example of passing non-serializable plugin functions to nextra, which is not supported when Turbopack is enabled.
```js
import nextra from 'nextra'
const withNextra = nextra({
mdxOptions: {
remarkPlugins: [myRemarkPlugin],
rehypePlugins: [myRehypePlugin],
recmaPlugins: [myRecmaPlugin]
}
})
```
--------------------------------
### MDX Static Rendering Example with GitHub Stars
Source: https://github.com/shuding/nextra/blob/main/examples/docs/src/content/features/ssg.mdx
This MDX code defines an async server component to fetch GitHub stars and embeds it directly into the content. The data is fetched at build time.
```mdx
export async function Stars() {
const response = await fetch(`https://api.github.com/repos/shuding/nextra`)
const repo = await response.json()
const stars = repo.stargazers_count || 0
return {stars}
}
> Nextra has stars on GitHub!
```
--------------------------------
### Configure SWR Cache Provider
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/advanced/cache.mdx
Example of providing a Map instance as the cache storage within SWRConfig.
```jsx
import useSWR, { SWRConfig } from 'swr'
function App() {
return (
new Map() }}>
)
}
```
--------------------------------
### Render OverviewPage Component
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/page.mdx
Renders the OverviewPage component, passing the filePath and a configuration object for various icons. This component is central to displaying guide content.
```javascript
```
--------------------------------
### Sorting Keys Example in _meta.js
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/file-conventions/meta-file/page.mdx
Demonstrates how JavaScript object key ordering can affect the final output. Numeric keys are sorted before string keys, and numeric keys are converted to strings.
```javascript
export default {
foo: '',
1992_10_21: '',
1: ''
}
```
```javascript
export default {
'1': '',
'19921021': '',
foo: ''
}
```
--------------------------------
### Implementing initFocus with AppState
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/advanced/react-native.mdx
Example implementation of initFocus using React Native's AppState to trigger revalidation when the app becomes active.
```jsx
import { AppState } from 'react-native'
// ...
new Map(),
isVisible: () => { return true },
initFocus(callback) {
let appState = AppState.currentState
const onAppStateChange = (nextAppState) => {
/* If it's resuming from background or inactive mode to active one */
if (appState.match(/inactive|background/) && nextAppState === 'active') {
callback()
}
appState = nextAppState
}
// Subscribe to the app state change events
const subscription = AppState.addEventListener('change', onAppStateChange)
return () => {
subscription.remove()
}
}
}}
>
```
--------------------------------
### File Tree Structure Example 2
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/getting-started.mdx
Represents a nested file structure where the posts-service folder is nested within the users-service folder, and both contain a schema.graphql file.
```jsx
```
--------------------------------
### Markdown Relative Link Example
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/link/page.mdx
Standard Markdown syntax for creating a relative link that Nextra will automatically process.
```markdown
Click [here](/about) to read more.
```
--------------------------------
### Compile and Render Mermaid MDX
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/advanced/mermaid/page.mdx
This example demonstrates how to compile MDX content containing a Mermaid code block and render it using the MDXRemote component with the Mermaid component. Ensure the Mermaid component is provided.
```javascript
import { compileMdx } from 'nextra/compile'
import { Mermaid } from 'nextra/components'
import { MDXRemote } from 'nextra/mdx-remote'
export async function Demo() {
const mermaidCodeblock = `
graph TD;
subgraph AA [Consumers]
A[Mobile app];
B[Web app];
C[Node.js client];
end
subgraph BB [Services]
E[REST API];
F[GraphQL API];
G[SOAP API];
end
Z[GraphQL API];
A --> Z;
B --> Z;
C --> Z;
Z --> E;
Z --> F;
Z --> G;
`
const rawJs = await compileMdx(`${mermaidCodeblock}
## Usage
~~~
${mermaidCodeblock}
~~~`)
return
}
```
--------------------------------
### Data Fetching with SWR Hook
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/getting-started.mdx
This refactored example uses a custom `useUser` hook with SWR. Data fetching logic is localized to components that need it, simplifying parent components and enabling automatic request deduplication and caching.
```jsx
// page component
function Page() {
return (
)
}
// child components
function Navbar() {
return (
...
)
}
function Content() {
const { user, isLoading } = useUser()
if (isLoading) return
return
)
}
```
--------------------------------
### Implement GitHub Alert Syntax
Source: https://github.com/shuding/nextra/blob/main/examples/blog/app/posts/(with-comments)/nextra-components/page.mdx
Use blockquote syntax to create GitHub-style alerts.
```markdown
> [!NOTE]
>
> Useful information that users should know, even when skimming content.
```
```markdown
> [!TIP]
>
> Helpful advice for doing things better or more easily.
```
```markdown
> [!IMPORTANT]
>
> Key information users need to know to achieve their goal.
```
```markdown
> [!WARNING]
>
> Urgent info that needs immediate user attention to avoid problems.
```
```markdown
> [!CAUTION]
>
> Advises about risks or negative outcomes of certain actions.
```
--------------------------------
### Configure table styling in next.config.mjs
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/advanced/table/page.mdx
Enable styling for standard HTML table elements by adding them to the whiteListTagsStyling configuration in your Nextra setup.
```js
import nextra from 'nextra'
const withNextra = nextra({
whiteListTagsStyling: ['table', 'thead', 'tbody', 'tr', 'th', 'td']
})
export default withNextra()
```
--------------------------------
### Import Blog Component
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/blog.mdx
Import the Blog component from the specified path. This component is used to render blog content.
```javascript
import { Blog } from '@app/_components/blog'
```
--------------------------------
### Conditionally Fetch Data with Null Key
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/conditional-fetching.md
Use `null` as the key to prevent SWR from starting a request. This is useful when a condition is not met.
```javascript
const { data } = useSWR(shouldFetch ? '/api/data' : null, fetcher)
```
--------------------------------
### Configure Typesense Indexing Script
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/search/typesense/page.mdx
Create a script to index your documentation into Typesense after the build. Ensure you provide your Typesense server URL and an Admin API key with write permissions.
```typescript
import { indexNextraToTypesense } from 'typesense-nextra-adapter'
indexNextraToTypesense({
serverConfig: {
nodes: [{ url: 'YOUR_TYPESENSE_SERVER_URL' }],
apiKey: 'YOUR_TYPESENSE_ADMIN_API_KEY' // Requires Write permissions
},
collectionName: 'nextra-docs'
})
```
--------------------------------
### Callout Component with Custom Emoji
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/callout.mdx
Shows how to customize the Callout component by adding a specific emoji. This example uses the French flag emoji.
```jsx
`…`
```
--------------------------------
### Render tables
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/guide/markdown/page.mdx
Create tables using pipes and hyphens to define columns and alignment.
```md
| Syntax | Description | Test Text |
| :------------ | :---------: | ----------: |
| Header | Title | Here's this |
| Paragraph | Text | And more |
| Strikethrough | | ~~Text~~ |
```
--------------------------------
### Example Npm2Yarn Code Block
Source: https://github.com/shuding/nextra/blob/main/docs/app/docs/advanced/npm2yarn/page.mdx
A sample code block with 'npm2yarn' metadata, intended to be processed by the remark-npm2yarn plugin. This block will be transformed into interactive tabs.
```markdown
```sh npm2yarn
npm i -D @graphql-eslint/eslint-plugin
```
```
--------------------------------
### Passing Objects as Keys
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/en/docs/arguments.mdx
Demonstrates passing objects as keys and using conditional fetching based on previous data.
```js
const { data: user } = useSWR(['/api/user', token], fetchWithToken)
// ...and then pass it as an argument to another useSWR hook
const { data: orders } = useSWR(
user ? ['/api/orders', user] : null,
fetchWithUser
)
```
```js
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
```
--------------------------------
### Paginación Optimizada con Precarga
Source: https://github.com/shuding/nextra/blob/main/examples/swr-site/content/es/docs/pagination.mdx
Mejora la UX de paginación precargando los datos de la siguiente página en un div oculto. SWR detecta la obtención de datos y los datos estarán disponibles instantáneamente al navegar.
```jsx
function App() {
const [pageIndex, setPageIndex] = useState(0)
return (