Change the base URL from localhost to the production URL. Implement a check for the build environment to use mock data for generating the sitemap during the build process. This ensures that sitemap is correctly populated with project routes even when the API is not available.
89 lines
2.3 KiB
TypeScript
89 lines
2.3 KiB
TypeScript
// portfolio/app/api/sitemap/route.tsx
|
|
import { NextResponse } from "next/server";
|
|
|
|
interface Project {
|
|
slug: string;
|
|
}
|
|
|
|
interface ProjectsData {
|
|
posts: Project[];
|
|
}
|
|
|
|
interface SitemapRoute {
|
|
url: string;
|
|
lastModified: string;
|
|
}
|
|
|
|
const baseUrl = "https://dki.one";
|
|
|
|
const generateSitemap = async (): Promise<SitemapRoute[]> => {
|
|
try {
|
|
// Static pages
|
|
const staticRoutes: SitemapRoute[] = [
|
|
{ url: `${baseUrl}/`, lastModified: new Date().toISOString() },
|
|
{
|
|
url: `${baseUrl}/privacy-policy`,
|
|
lastModified: new Date().toISOString(),
|
|
},
|
|
{
|
|
url: `${baseUrl}/legal-notice`,
|
|
lastModified: new Date().toISOString(),
|
|
},
|
|
];
|
|
|
|
// Check if running in build environment
|
|
if (process.env.IS_BUILD) {
|
|
// Use mock data during build
|
|
const mockProjectsData: ProjectsData = {
|
|
posts: [
|
|
{ slug: "project-1" },
|
|
{ slug: "project-2" },
|
|
{ slug: "project-3" },
|
|
],
|
|
};
|
|
const projectRoutes: SitemapRoute[] = mockProjectsData.posts.map(
|
|
(project) => ({
|
|
url: `${baseUrl}/projects/${project.slug}`,
|
|
lastModified: new Date().toISOString(),
|
|
}),
|
|
);
|
|
return [...staticRoutes, ...projectRoutes];
|
|
}
|
|
|
|
// Fetch project data from your API
|
|
console.log("Fetching project data from API...");
|
|
const response = await fetch(`${baseUrl}/api/fetchAllProjects`);
|
|
if (!response.ok) {
|
|
throw new Error(
|
|
`Failed to fetch projects from Ghost: ${response.statusText}`,
|
|
);
|
|
}
|
|
const projectsData = (await response.json()) as ProjectsData;
|
|
console.log("Fetched project data:", projectsData);
|
|
|
|
// Generate dynamic routes for projects
|
|
const projectRoutes: SitemapRoute[] = projectsData.posts.map((project) => ({
|
|
url: `${baseUrl}/projects/${project.slug}`,
|
|
lastModified: new Date().toISOString(),
|
|
}));
|
|
|
|
return [...staticRoutes, ...projectRoutes];
|
|
} catch (error) {
|
|
console.error("Error generating sitemap:", error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export async function GET() {
|
|
try {
|
|
const sitemap = await generateSitemap();
|
|
return NextResponse.json(sitemap);
|
|
} catch (error) {
|
|
console.error("Failed to generate sitemap:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to generate sitemap" },
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|