Next.js Discord

Discord Forum

Autogenerate sitemap with app router.

Unanswered
Yacare Caiman posted this in #help-forum
Open in Discord
Avatar
Yacare CaimanOP
Is there a way to autogenerate sitemap without the need to manually declare every route in app/sitemap.ts ?

2 Replies

Avatar
B33fb0n3
I will use this one: https://www.npmjs.com/package/next-sitemap
That looks very good for me. It's postbuild and app router @Yacare Caiman
Avatar
Z4NR34L
Are you using any CMS or helper like contentlayer? If yes, you will only need make an array with static routes and there is an easy trick for app/sitemap.ts:

app/sitemap.ts
import { getStatusReports } from '@/interface/betterstack';
import { urls } from '@/site.config';

export default async function sitemap(): Promise<{ url: string }[]> {
  const { data: incidents } = await getStatusReports();
  return [
    ...urls,
    ...incidents.map((incident) => ({
      url: `https://www.zanreal.net/status/incident/${incident.id}`,
    })),
  ];
}


site.config.ts
const routes = ['', 'contact', 'blog', 'status', 'status/incident'].map(
  (page) => ({
    url: `https://www.zanreal.net/${page}`,
  }),
);

const pages = allPages.map((page) => ({
  url: `https://www.zanreal.net/${page.slug}`,
}));
const posts = allPosts.map((post) => ({
  url: `https://www.zanreal.net/blog/${post.slug}`,
}));

export const urls = [...routes, ...pages, ...posts];


And I'm not touching it anymore currently 😄 Also I'm using those urls exported in site.config for other things like crons.