31 lines
1.2 KiB
JavaScript
31 lines
1.2 KiB
JavaScript
// app/api/sitemap/route.js
|
|
import { getAllSlugs } from '@/utils/data';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
|
|
export async function POST(req) {
|
|
const secret = req.headers.get('x-revalidate-secret');
|
|
if (secret !== process.env.REVALIDATE_TOKEN) {
|
|
return new Response('Unauthorized', { status: 401 });
|
|
}
|
|
const slugs = await getAllSlugs();
|
|
const siteUrl = process.env.SITE_URL || 'https://yourdomain.com';
|
|
const urls = slugs.map(slugArr => {
|
|
if (slugArr.length === 1 && slugArr[0] === '/') {
|
|
return '/';
|
|
}
|
|
return '/' + slugArr.join('/');
|
|
});
|
|
|
|
let uniqueUrls = Array.from(new Set(urls));
|
|
if (!uniqueUrls.includes('/')) {
|
|
uniqueUrls.unshift('/');
|
|
} else {
|
|
uniqueUrls = uniqueUrls.filter(url => url !== '/');
|
|
uniqueUrls.unshift('/');
|
|
}
|
|
|
|
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${uniqueUrls.map(url => `\n <url>\n <loc>${siteUrl}${url}</loc>\n <changefreq>weekly</changefreq>\n <priority>0.7</priority>\n </url>`).join('')}\n</urlset>`;
|
|
fs.writeFileSync(path.join(process.cwd(), 'public/sitemap.xml'), sitemap, 'utf8');
|
|
return new Response('Sitemap regenerated', { status: 200 });
|
|
} |