Unverified Commit d6d84be2 authored by Joseph's avatar Joseph Committed by GitHub

Remove more examples (#89709)

Removing examples that we are not using, or maintaining anymore.
parent a0b5d9ad
......@@ -747,93 +747,6 @@ export default withMDX(nextConfig)
>
> remark and rehype plugins without serializable options cannot be used yet with [Turbopack](/docs/app/api-reference/turbopack), because JavaScript functions can't be passed to Rust.
## Remote MDX
If your MDX files or content lives _somewhere else_, you can fetch it dynamically on the server. This is useful for content stored in a CMS, database, or anywhere else. A community package for this use is [`next-mdx-remote-client`](https://github.com/ipikuka/next-mdx-remote-client?tab=readme-ov-file#the-part-associated-with-nextjs-app-router).
> **Good to know**: Please proceed with caution. MDX compiles to JavaScript and is executed on the server. You should only fetch MDX content from a trusted source, otherwise this can lead to remote code execution (RCE).
The following example uses `next-mdx-remote-client`:
<AppOnly>
```tsx filename="app/mdx-page-remote/page.tsx" switcher
import { MDXRemote } from 'next-mdx-remote-client/rsc'
export default async function RemoteMdxPage() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https://...')
const markdown = await res.text()
return <MDXRemote source={markdown} />
}
```
```jsx filename="app/mdx-page-remote/page.js" switcher
import { MDXRemote } from 'next-mdx-remote-client/rsc'
export default async function RemoteMdxPage() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https://...')
const markdown = await res.text()
return <MDXRemote source={markdown} />
}
```
</AppOnly>
<PagesOnly>
```tsx filename="pages/mdx-page-remote.tsx" switcher
import {
serialize,
type SerializeResult,
} from 'next-mdx-remote-client/serialize'
import { MDXClient } from 'next-mdx-remote-client'
type Props = {
mdxSource: SerializeResult
}
export default function RemoteMdxPage({ mdxSource }: Props) {
if ('error' in mdxSource) {
// either render error UI or throw `mdxSource.error`
}
return <MDXClient {...mdxSource} />
}
export async function getStaticProps() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https:...')
const mdxText = await res.text()
const mdxSource = await serialize({ source: mdxText })
return { props: { mdxSource } }
}
```
```jsx filename="pages/mdx-page-remote.js" switcher
import { serialize } from 'next-mdx-remote-client/serialize'
import { MDXClient } from 'next-mdx-remote-client'
export default function RemoteMdxPage({ mdxSource }) {
if ('error' in mdxSource) {
// either render error UI or throw `mdxSource.error`
}
return <MDXClient {...mdxSource} />
}
export async function getStaticProps() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https:...')
const mdxText = await res.text()
const mdxSource = await serialize({ source: mdxText })
return { props: { mdxSource } }
}
```
</PagesOnly>
Navigating to the `/mdx-page-remote` route should display your rendered MDX.
## Deep Dive: How do you transform markdown into HTML?
React does not natively understand markdown. The markdown plaintext needs to first be transformed into HTML. This can be accomplished with `remark` and `rehype`.
......
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# MDX Remote Example
This example shows how a simple blog might be built using the [next-mdx-remote](https://github.com/hashicorp/next-mdx-remote) library, which allows mdx content to be loaded via [`generateStaticParams`](https://nextjs.org/docs/app/api-reference/functions/generate-static-params). The mdx content is loaded from a local folder, but it could be loaded from a database or anywhere else.
## Deploy your own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/mdx-remote&project-name=mdx-remote&repository-name=mdx-remote)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) to bootstrap the example:
```bash
npx create-next-app --example mdx-remote mdx-remote-app
```
```bash
yarn create next-app --example mdx-remote mdx-remote-app
```
```bash
pnpm create next-app --example mdx-remote mdx-remote-app
```
```bash
bunx create-next-app --example mdx-remote mdx-remote-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/app/building-your-application/deploying)).
## Notes
### Conditional custom components
When using `next-mdx-remote`, you can pass custom components to the MDX renderer. However, some pages/MDX files might use components that are used infrequently, or only on a single page. To avoid loading those components on every MDX page, you can use [`next/dynamic`](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic) to conditionally load them.
```typescript
import dynamic from "next/dynamic";
import Test from "@/components/test";
import { MDXRemote, type MDXRemoteProps } from 'next-mdx-remote/rsc'
const SomeHeavyComponent = dynamic(() => import("../component/SomeHeavyComponent"));
const defaultComponents = { Test };
export function CustomMDX(props: MDXRemoteProps) {
const componentNames = [
/<SomeHeavyComponent/.test(props.source as string) ? "SomeHeavyComponent" : "",
].filter(Boolean);
const components = {
...defaultComponents,
SomeHeavyComponent: componentNames.includes("SomeHeavyComponent")
? SomeHeavyComponent
: () => null,
};
return <MDXRemote {...props} components={components} />;
}
```
import { notFound } from "next/navigation";
import { CustomMDX } from "@/components/mdx";
import { getPosts } from "@/lib/utils";
import styles from "./page.module.css";
import Link from "next/link";
export function generateStaticParams() {
const posts = getPosts();
return posts.map((post) => ({
slug: post.slug,
}));
}
export default async function Blog({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const post = getPosts().find((post) => post.slug === slug);
if (!post) {
notFound();
}
return (
<>
<header>
<nav>
<Link href="/">👈 Go back home</Link>
</nav>
</header>
<main>
<h1 className={styles.postHeader}>{post.metadata.title}</h1>
{post.metadata.description && (
<p className={styles.description}>{post.metadata.description}</p>
)}
<article>
<CustomMDX source={post.content} />
</article>
</main>
</>
);
}
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
html,
body {
font: 100%/1.5 system-ui;
max-width: 100vw;
overflow-x: hidden;
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
max-width: 36rem;
margin: 0 auto;
padding: 1.5rem;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
a {
color: inherit;
text-decoration-thickness: 2px;
}
a:hover {
color: royalblue;
text-decoration-color: currentcolor;
}
p {
margin-bottom: 1.5rem;
}
code {
font-family: Menlo;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
}
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "MDX Remote App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable}`}>
{children}
</body>
</html>
);
}
import Link from "next/link";
import { getPosts } from "@/lib/utils";
export default function Home() {
const posts = getPosts();
return (
<main>
<h1>Home Page</h1>
<p>
Click the link below to navigate to a page generated by{" "}
<code>next-mdx-remote</code>.
</p>
<ul>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/${post.slug}`}>{post.metadata.title}</Link>
</li>
))}
</ul>
</main>
);
}
---
title: Example Post
description: This frontmatter description will appear below the title
---
This is an example post, with with a [link](https://nextjs.org) and a React component:
<Greet name="next-mdx-remote" />
Links are rendered using a custom component passed to `next-mdx-remote`.
Go back [home](/).
---
title: Hello World
---
This is an example post. There's another one [here](/example-post).
.div {
background-color: #111;
border-radius: 0.5em;
color: #fff;
margin-bottom: 1.5em;
padding: 0.5em 0.75em;
}
import styles from "./greet.module.css";
export function Greet({ name = "world" }: { name: string }) {
return <div className={styles.div}>Hello, {name}!</div>;
}
.a {
color: tomato;
text-decoration-color: rgba(0, 0, 0, 0.4);
}
import React from "react";
import Link from "next/link";
import { MDXRemote, type MDXRemoteProps } from "next-mdx-remote/rsc";
import { Greet } from "./greet";
import styles from "./mdx.module.css";
function CustomLink({
href,
children,
...props
}: React.LinkHTMLAttributes<HTMLAnchorElement>) {
if (href?.startsWith("/")) {
return (
<Link href={href} className={styles.a} {...props}>
{children}
</Link>
);
}
if (href?.startsWith("#")) {
return (
<a href={href} className={styles.a} {...props}>
{children}
</a>
);
}
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className={styles.a}
{...props}
>
{children}
</a>
);
}
export function CustomMDX(props: MDXRemoteProps) {
const components = {
a: CustomLink,
Greet: Greet,
};
return (
<MDXRemote
{...props}
components={{ ...components, ...(props.components || {}) }}
/>
);
}
import fs from "node:fs";
import path from "node:path";
type Metadata = {
title: string;
description?: string;
};
function parseFrontmatter(fileContent: string) {
const frontmatterRegex = /---\s*([\s\S]*?)\s*---/;
const content = fileContent.replace(frontmatterRegex, "").trim();
const match = frontmatterRegex.exec(fileContent);
const frontMatterBlock = match![1];
const frontMatterLines = frontMatterBlock.trim().split("\n");
const metadata: Partial<Metadata> = {};
frontMatterLines.forEach((line) => {
const [key, ...valueArr] = line.split(": ");
let value = valueArr.join(": ").trim();
value = value.replace(/^['"](.*)['"]$/, "$1"); // Remove quotes
metadata[key.trim() as keyof Metadata] = value;
});
return { metadata: metadata as Metadata, content: content };
}
function getMDXFiles(dir: fs.PathLike) {
return fs.readdirSync(dir).filter((file) => path.extname(file) === ".mdx");
}
function readMDXFile(filePath: fs.PathOrFileDescriptor) {
const rawContent = fs.readFileSync(filePath, "utf-8");
return parseFrontmatter(rawContent);
}
function getMDXData(dir: fs.PathLike) {
const mdxFiles = getMDXFiles(dir);
return mdxFiles.map((file) => {
const { metadata, content } = readMDXFile(path.join(dir.toString(), file));
const slug = path.basename(file, path.extname(file));
return {
metadata,
slug,
content,
};
});
}
export function getPosts() {
return getMDXData(path.join(process.cwd(), "app", "posts"));
}
{
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"next-mdx-remote": "^5.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"typescript": "^5.7.2"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Contentlayer Example
This example shows how to integrate Contentlayer in Next.js. Learn more about [Contentlayer](https://www.contentlayer.dev/docs).
## Deploy your own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-contentlayer&project-name=with-contentlayer&repository-name=with-contentlayer)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example with-contentlayer with-contentlayer-app
```
```bash
yarn create next-app --example with-contentlayer with-contentlayer-app
```
```bash
pnpm create next-app --example with-contentlayer with-contentlayer-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import { defineDocumentType, makeSource } from "contentlayer/source-files";
const computedFields = {
slug: {
type: "string",
resolve: (doc) => doc._raw.sourceFileName.replace(/\.md$/, ""),
},
};
export const Post = defineDocumentType(() => ({
name: "Post",
filePathPattern: `**/*.md`,
fields: {
title: { type: "string", required: true },
date: { type: "string", required: true },
},
computedFields,
}));
export default makeSource({
contentDirPath: "posts",
documentTypes: [Post],
});
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"contentlayer/generated": ["./.contentlayer/generated"]
}
},
"include": [".contentlayer/generated"]
}
const { withContentlayer } = require("next-contentlayer");
module.exports = withContentlayer({});
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"contentlayer": "^0.2.4",
"next": "latest",
"next-contentlayer": "^0.3.4",
"react": "18.0.0",
"react-dom": "18.0.0"
}
}
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
import Link from "next/link";
import Head from "next/head";
import { allPosts } from "contentlayer/generated";
import { pick } from "@contentlayer/client";
import utilStyles from "../styles/utils.module.css";
export default function Home({ posts }) {
return (
<>
<Head>
<title>Home</title>
</Head>
<section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
<h2 className={utilStyles.headingLg}>Blog</h2>
<ul className={utilStyles.list}>
{posts.map(({ slug, date, title }) => (
<li className={utilStyles.listItem} key={slug}>
<Link href={`/posts/${slug}`}>{title}</Link>
<br />
<small className={utilStyles.lightText}>{date}</small>
</li>
))}
</ul>
</section>
</>
);
}
export async function getStaticProps() {
const posts = allPosts.map((post) => pick(post, ["title", "date", "slug"]));
return { props: { posts } };
}
import Head from "next/head";
import { allPosts } from "contentlayer/generated";
import utilStyles from "../../styles/utils.module.css";
export default function Post({ post }) {
return (
<>
<Head>
<title>{post.title}</title>
</Head>
<article>
<h1 className={utilStyles.headingXl}>{post.title}</h1>
<div className={utilStyles.lightText}>{post.date}</div>
<div dangerouslySetInnerHTML={{ __html: post.body.html }} />
</article>
</>
);
}
export async function getStaticPaths() {
return {
paths: allPosts.map((p) => ({ params: { id: p.slug } })),
fallback: false,
};
}
export async function getStaticProps({ params }) {
const post = allPosts.find((post) => post.slug === params?.id);
return { props: { post } };
}
---
title: "Two Forms of Pre-rendering"
date: "2020-01-01"
---
Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page.
- **Static Generation** is the pre-rendering method that generates the HTML at **build time**. The pre-rendered HTML is then _reused_ on each request.
- **Server-side Rendering** is the pre-rendering method that generates the HTML on **each request**.
Importantly, Next.js lets you **choose** which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.
---
title: "When to Use Static Generation vs Server-side Rendering"
date: "2020-01-02"
---
We recommend using **Static Generation** (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.
You can use Static Generation for many types of pages, including:
- Marketing pages
- Blog posts
- E-commerce product listings
- Help and documentation
You should ask yourself: "Can I pre-render this page **ahead** of a user's request?" If the answer is yes, then you should choose Static Generation.
On the other hand, Static Generation is **not** a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.
In that case, you can use **Server-Side Rendering**. It will be slower, but the pre-rendered page will always be up-to-date. Or you can skip pre-rendering and use client-side JavaScript to populate data.
html,
body {
padding: 0;
margin: 0;
font-family:
-apple-system,
BlinkMacSystemFont,
Segoe UI,
Roboto,
Oxygen,
Ubuntu,
Cantarell,
Fira Sans,
Droid Sans,
Helvetica Neue,
sans-serif;
line-height: 1.6;
font-size: 18px;
}
* {
box-sizing: border-box;
}
a {
color: #0070f3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.heading2Xl {
font-size: 2.5rem;
line-height: 1.2;
font-weight: 800;
letter-spacing: -0.05rem;
margin: 1rem 0;
}
.headingXl {
font-size: 2rem;
line-height: 1.3;
font-weight: 800;
letter-spacing: -0.05rem;
margin: 1rem 0;
}
.headingLg {
font-size: 1.5rem;
line-height: 1.4;
margin: 1rem 0;
}
.headingMd {
font-size: 1.2rem;
line-height: 1.5;
}
.borderCircle {
border-radius: 9999px;
}
.colorInherit {
color: inherit;
}
.padding1px {
padding-top: 1px;
}
.list {
list-style: none;
padding: 0;
margin: 0;
}
.listItem {
margin: 0 0 1.25rem;
}
.lightText {
color: #666;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment