Next.js 14 App Router站点地图动态路由参数无法访问及路径疑问
Next.js 14 App Router 站点地图迁移问题解答
问题1:动态参数params为什么无法访问?
你当前的文件结构app/sitemaps/[categoryId]/category/sitemap.ts存在两个核心问题:
- Next.js的
sitemap.ts约定式文件,只会自动注入当前路由层级的动态段参数,[categoryId]属于父路由的动态段,无法自动传递到子路由下的sitemap.ts中。 - 该文件结构对应的访问路径是
/sitemaps/124/category/sitemap.xml,和你期望保留的/sitemaps/124/category.xml路径不匹配,同时父级参数的传递链路被打断。
解决方式:将生成站点地图的文件直接放在app/sitemaps/[categoryId]/目录下,确保动态参数能被正确捕获。
问题2:站点地图路径必须以[...]/sitemap.xml结尾吗?能否使用自定义名称?
不是必须的,你可以使用自定义名称(比如category.xml),但不能依赖Next.js提供的sitemap.ts约定式文件——因为它会固定映射到路径末尾的sitemap.xml。
要实现自定义名称的站点地图,需要用route.ts手动生成XML响应:
- 在
app/sitemaps/[categoryId]/目录下创建category.xml/route.ts文件(对应你期望的访问路径) - 在文件中编写逻辑,返回符合站点地图规范的XML内容,同时可正常获取
params中的categoryId参数
示例代码(app/sitemaps/[categoryId]/category.xml/route.ts):
import { SiteURL, getCategoryLink } from '@/utils/your-utils'; import type { ICategory } from '@/types'; // 替换为你的数据获取函数 async function fetchCategories(categoryId: number): Promise<ICategory[]> { // 你的数据请求逻辑 } export async function GET({ params }: { params: { categoryId: string } }) { const categoryId = parseInt(params.categoryId); const categories = await fetchCategories(categoryId); const sitemapXml = `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ${categories.map(category => ` <url> <loc>${SiteURL}${getCategoryLink(category)}</loc> <lastmod>${new Date().toISOString()}</lastmod> <changefreq>daily</changefreq> <priority>1.0</priority> </url> `).join('')} </urlset>`; return new Response(sitemapXml, { headers: { 'Content-Type': 'application/xml', }, }); }
完成后即可通过https://localhost:3000/sitemaps/124/category.xml正常访问,且categoryId参数能正确获取。
内容的提问来源于stack exchange,提问作者SANGEETH KUMAR S G
相关产品推荐
相关产品推荐

