<!-- Generated from zh/llms-txt-nextjs/index.html. The canonical document is the HTML page. -->

- [ 首页 ](/zh/) 
/
- [ 如何创建 llms.txt ](/zh/how-to-create/) 
/
- Next.js            
# Next.js 中的 `llms.txt`

只需几分钟即可向 Next.js 项目添加 llms.txt，可将其作为静态资源，也可使用动态 Route Handler。

最近更新: 2026年4月22日

本页内容

- [ 两种方法 ](#overview)
- [ 方法 1：/public/ 中的静态文件 ](#static)
- [ 方法 2：App Router Route Handler ](#route-handler)
- [ Pages Router 替代方案 ](#pages-router)
- [ 添加 llms-full.txt ](#llms-full)
- [ 验证设置 ](#verify)            
## 两种方法

Next.js 提供两种简洁方式来提供 `llms.txt` 在 `/llms.txt`:

- **静态文件放在 `/public/`**，这是最简单的方法。手动编写文件，
或在构建时生成。App Router 和 Pages Router 均适用。没有 运行时开销。 
- **App Router 路由处理程序**一个 TypeScript 文件位于
`app/llms.txt/route.ts` 会从你的数据源 （MDX 文件、CMS、数据库）动态生成内容。最适合内容经常变化的情况。   
对大多数网站来说，位于 `/public/` 是正确选择。仅当你希望在构建时或请求时根据网站数据自动生成内容，才使用
Route Handler。

## 方法 1：/public/ 中的静态文件

Next.js 会将 `/public/` 目录位于你的域名根目录。位于 `/public/llms.txt` 可通过以下地址访问：
`https://yourdomain.com/llms.txt`
无需任何额外配置。

- 创建文件： `touch public/llms.txt` 
- 先编写你的 `llms.txt` 内容（请参阅 [操作指南](/zh/how-to-create/) 和
[生成器](/zh/generator/) ，了解正确格式）：   
```
# Your Site Name

> One-sentence description of your site for LLM context.

## Core pages

- [Page title](https://yourdomain.com/page/): brief description.
- [Another page](https://yourdomain.com/other/): brief description.

## Optional

- [About](https://yourdomain.com/about/): who maintains this site.

```

- 提交文件并部署。完成。     
示例

Content-Type 响应头

Next.js 将提供服务  /public/llms.txt  与  Content-Type: text/plain 
自动设置（依据  .txt  扩展）。无需额外的头部配置。

## 方法 2：App Router 路由处理程序

如果你希望生成 `llms.txt` 以编程方式生成，例如读取内容目录中的所有 MDX 文件，请使用 Route
Handler。

创建文件 `app/llms.txt/route.ts`:

```
import { NextResponse } from 'next/server';

export const dynamic = 'force-static'; // generate at build time

export async function GET() {
// Build your content. Here: hardcoded; in practice: read from MDX, CMS, etc.
const content = `# Your Site Name

> Description of your site.

## Core pages

- [Getting started](https://yourdomain.com/docs/getting-started/): installation and first steps.
- [API reference](https://yourdomain.com/docs/api/): full endpoint reference.
`;

return new NextResponse(content, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
// Optional: cache for 1 hour in production
'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
},
});
}

```

设置 `dynamic = 'force-static'` 指示 Next.js 在构建时渲染此路由，而不是在每次请求时渲染。如果确实需要动态内容（在请求时从实时数据库获取），请删除这一行。

备注

从 MDX 文件自动生成

若要根据 MDX 内容目录自动生成页面列表，请将硬编码字符串替换为读取内容源的逻辑：
const files = fs.readdirSync('content/docs')  → 提取标题和 slug → 构建 Markdown 列表。这样可使
llms.txt  与实际页面自动保持同步。

## Pages Router 替代方案

如果你使用 Next.js Pages Router（早于 App Router），最简单的方式仍然是放在以下位置的静态文件： `/public/`。Route Handler 文件约定仅存在于 App Router 中。

若要通过 Pages Router 动态生成，可以使用自定义服务器（Express 或 Fastify）或 `getServerSideProps`支持自定义内容类型的后端页面，但与静态文件相比，这会显著增加复杂性。请继续使用 `/public/llms.txt`
用于 Pages Router 项目。

## 添加 llms-full.txt

[`llms-full.txt`](/zh/llms-full-txt/) 会将关键页面的完整内容内联到单个文件中。在
Next.js App Router 中：

```
// app/llms-full.txt/route.ts
import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export const dynamic = 'force-static';

export async function GET() {
// Example: read MDX files from content/docs and concatenate them
const docsDir = path.join(process.cwd(), 'content/docs');
const files = fs.readdirSync(docsDir).filter(f => f.endsWith('.mdx'));

const sections = files.map(file => {
const content = fs.readFileSync(path.join(docsDir, file), 'utf8');
const slug = file.replace('.mdx', '');
return `## https://yourdomain.com/docs/${slug}/\n\n${content}`;
});

const body = `# yourdomain.com, full content\n\n${sections.join('\n\n---\n\n')}`;

return new NextResponse(body, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}

```

## 验证设置

部署后，请验证您的文件是否可访问且格式正确：

- 访问 `https://yourdomain.com/llms.txt` ，你应该会在浏览器中看到纯文本。 
- 检查 HTTP 标头： `curl -I https://yourdomain.com/llms.txt` 应显示
`Content-Type: text/plain` 和一个 200 状态码。 
- 将 URL 粘贴到 [llmtxt.info 验证器](/zh/validator/) 以检查规范符合性。 
- 检查该 `llms.txt` 未被阻止于你的 `public/robots.txt`.   
## 继续阅读

- [如何创建 llms.txt](/zh/how-to-create/)，适用于所有框架的通用指南，带有模板。 
- [什么是 llms-full.txt？](/zh/llms-full-txt/)，即完整语料的补充文件。 
- [验证器](/zh/validator/)，按照规范检查你的文件。 
- [最佳实践](/zh/best-practices/)，包括该包含什么以及该避免什么。        
## 来源

- [ Next.js 文档，/public/ 中的静态资源 ](https://nextjs.org/docs/app/api-reference/file-conventions/public-folder)
- [ Next.js 文档，Route Handlers ](https://nextjs.org/docs/app/api-reference/file-conventions/route)
- [ llmstxt.org，规范参考 ](https://llmstxt.org/)
