go to index

next.js 13生成站点地图sitemap.xml

read time 1 min read
nextjs sitemap 地图

适用版本

此方法适用于 Next.js 13.3 及以上版本。

参考代码:app/sitemap.js

typescript
import api from "./axios/api";

const URL = "https://www.jason-z.com";

// 获取文章数据
async function getPosts() {
    try {
        const res = await api.get("/posts?sort[0]=createdAt:desc");
        if (res.status === 200) {
            return res.data.data;
        }
    } catch (e) {
        console.error("获取文章数据失败:", e);
    }

    return [];
}

export default async function sitemap() {
    const postsData = await getPosts();

    // 处理文章数据
    const posts = postsData.map(({ id, attributes }) => ({
        url: `${URL}/posts/${attributes?.slug}`,
        lastModified: attributes?.updatedAt,
    }));

    // 处理静态路由
    const routes = ["", "/blog"].map((route) => ({
        url: `${URL}${route}`,
        lastModified: new Date().toISOString(),
    }));

    // 返回合并后的站点地图数据
    return [...routes, ...posts];
}

访问站点地图

访问 https://www.jason-z.com/sitemap.xml 即可查看生成的站点地图。