'How to rewrite or change the slug using getStaticProps for only one slug using Next js
I am working on my Next JS project. I have all my slugs which I map through and create all pages using the catch-all route from Next. However, I have a page with slug /home I would like to rewrite this path to the root path like so "/" How can I change the slug inside the getStaticProps? Currently I have to go to /home to see my homepage but I need this to be the absolute root path.
Code:
import { getClient, usePreviewSubscription } from "../lib/sanity";
import { groq } from "next-sanity";
import { getQueryFromSlug } from "../lib/helpers";
import dynamic from "next/dynamic";
const PageSingle = dynamic(() => import("../components/layouts/PageSingle"));
const NewsSingle = dynamic(() => import("../components/layouts/NewsSingle"));
interface Props {
data: any;
preview: boolean;
}
export default function Page({ data, preview }: Props) {
const { data: pageData } = usePreviewSubscription(data?.query, {
params: data?.queryParams ?? {},
initialData: data?.pageData,
enabled: preview,
});
const { docType } = data;
return (
<>
{docType === "home" && <PageSingle page={pageData} />}
{docType === "page" && <PageSingle page={pageData} />}
{docType === "article" && <NewsSingle post={pageData} />}
{docType === "case" && <NewsSingle post={pageData} />}
</>
);
}
export async function getStaticPaths() {
const pageQueries = await getClient().fetch(
groq`*[_type in ["homePage", "page", "article", "case"] && defined(slug.current)][].slug.current`
);
// Split the slug strings to arrays (as required by Next.js)
const paths = pageQueries.map((slug: string) => ({
params: { slug: slug.split("/").filter((p) => p) },
}));
return { paths, fallback: false };
}
export async function getStaticProps({ params }: any) {
// Every website has a bunch of global content that every page needs, too!
// const globalSettings = await client.fetch(globalSettingsQuery);
// A helper function to work out what query we should run based on this slug
const { query, queryParams, docType } = getQueryFromSlug(params.slug);
// Get the initial data for this page, using the correct query
const pageData = await getClient().fetch(query, queryParams);
return {
props: {
data: { query, queryParams, docType, pageData },
},
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
