refactor(sitemap): improve sitemap generation and error handling; rename sitemap file
This commit is contained in:
76
app/sitemap.xml/route.tsx
Normal file
76
app/sitemap.xml/route.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import {NextResponse} from "next/server";
|
||||
|
||||
interface SitemapRoute {
|
||||
url: string;
|
||||
lastModified: string;
|
||||
changeFrequency?:
|
||||
| "always"
|
||||
| "hourly"
|
||||
| "daily"
|
||||
| "weekly"
|
||||
| "monthly"
|
||||
| "yearly"
|
||||
| "never";
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
const baseUrl = "https://dki.one";
|
||||
|
||||
export async function GET() {
|
||||
console.log("Generating sitemap...");
|
||||
|
||||
const staticRoutes: SitemapRoute[] = [
|
||||
{url: `${baseUrl}/`, lastModified: new Date().toISOString(), changeFrequency: "weekly", priority: 1.0},
|
||||
{
|
||||
url: `${baseUrl}/privacy-policy`,
|
||||
lastModified: new Date().toISOString(),
|
||||
changeFrequency: "yearly",
|
||||
priority: 0.3
|
||||
},
|
||||
{
|
||||
url: `${baseUrl}/legal-notice`,
|
||||
lastModified: new Date().toISOString(),
|
||||
changeFrequency: "yearly",
|
||||
priority: 0.3
|
||||
},
|
||||
];
|
||||
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/sitemap`);
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch dynamic routes: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const dynamicRoutes = (await response.json()) as SitemapRoute[];
|
||||
const sitemap = [...staticRoutes, ...dynamicRoutes];
|
||||
|
||||
return new NextResponse(generateXml(sitemap), {
|
||||
headers: {"Content-Type": "application/xml"},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching dynamic routes, using fallback:", error);
|
||||
return new NextResponse(generateXml(staticRoutes), {
|
||||
headers: {"Content-Type": "application/xml"},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function generateXml(routes: SitemapRoute[]): string {
|
||||
const xmlHeader = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||
const urlsetOpen = '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">';
|
||||
const urlsetClose = '</urlset>';
|
||||
|
||||
const urlEntries = routes
|
||||
.map(
|
||||
(route) => `
|
||||
<url>
|
||||
<loc>${route.url}</loc>
|
||||
<lastmod>${route.lastModified}</lastmod>
|
||||
${route.changeFrequency ? `<changefreq>${route.changeFrequency}</changefreq>` : ""}
|
||||
${route.priority ? `<priority>${route.priority}</priority>` : ""}
|
||||
</url>`
|
||||
)
|
||||
.join("");
|
||||
|
||||
return `${xmlHeader}${urlsetOpen}${urlEntries}${urlsetClose}`;
|
||||
}
|
||||
Reference in New Issue
Block a user