Skip to content

Instantly share code, notes, and snippets.

@ChangoMan
Created August 21, 2023 06:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Next.js App Router Sitemap.js
import { MetadataRoute } from 'next'
import { getAllArticles } from '@/lib/articles'
const WEBSITE_HOST_URL = process.env.SITE_URL || 'https://travelxfamily.com'
type changeFrequency =
| 'always'
| 'hourly'
| 'daily'
| 'weekly'
| 'monthly'
| 'yearly'
| 'never'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
let articles = await getAllArticles()
const changeFrequency = 'daily' as changeFrequency
const posts = articles.map(({ slug, date }) => ({
url: `${WEBSITE_HOST_URL}/posts/${slug}`,
lastModified: date,
changeFrequency,
}))
const routes = ['', '/about', '/posts'].map((route) => ({
url: `${WEBSITE_HOST_URL}${route}`,
lastModified: new Date().toISOString(),
changeFrequency,
}))
return [...routes, ...posts]
}
@LeMoussel
Copy link

What is @/lib/articles?

@ChangoMan
Copy link
Author

What is @/lib/articles?

import glob from 'fast-glob'

interface Article {
  title: string
  description: string
  author: string
  date: string
}

export interface ArticleWithSlug extends Article {
  slug: string
}

export async function importArticle(
  articleFilename: string,
): Promise<ArticleWithSlug> {
  let { article } = (await import(`../app/posts/${articleFilename}`)) as {
    default: React.ComponentType
    article: Article
  }

  return {
    slug: articleFilename.replace(/(\/page)?\.mdx$/, ''),
    ...article,
  }
}

export async function getAllArticles() {
  let articleFilenames = await glob('*/page.mdx', {
    cwd: './src/app/posts',
  })

  let articles = await Promise.all(articleFilenames.map(importArticle))

  return articles.sort((a, z) => +new Date(z.date) - +new Date(a.date))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment