When using getStaticProps
, it's important to note that on the home page, your params.page
will be undefined due to the dynamic route setup. To handle this scenario, you can make a simple adjustment:
export async function getStaticProps({ params }) {
const pageSlug = params.page ?? "homepage"
const pages = await fetchAPI(`/pages?slug=${pageSlug}`);
return {
props: { page: pages[0] },
revalidate: 1,
};
}
Solution for Redirecting 404 Pages to Homepage
In response to a comment expressing concerns about displaying the homepage instead of a 404 error page when accessing non-existent URLs, there are several approaches you can consider:
Redirecting to Homepage on 404 (Recommended)
You can implement a redirect to the homepage if the requested page is not found in your pages
data. This method is preferred as it avoids duplicate content issues and unnecessary processing:
export async function getStaticProps({ params }) {
const pageSlug = params.page ?? "homepage"
const pages = await fetchAPI(`/pages?slug=${pageSlug}`);
if(!pages || !pages.length > 0) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: { page: pages[0] },
revalidate: 1,
};
}
The recommended approach ensures a smooth user experience without compromising SEO performance.
Using 404.js (or 404.tsx) for Redirection
Create a custom 404 page file like 404.js or 404.tsx which Next.js utilizes when encountering a 404 error. You can leverage the getStaticProps
function to redirect to the homepage:
// 404.js
export default function FourOhFourPage() {
return null
}
export async function getStaticProps({ params }) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
Displaying Home Page Content for Any 404 URL
An alternative approach involves querying the API for the homepage content if no valid page is found initially. While this may result in an additional API call, it can be managed by setting up canonical URLs to avoid SEO penalties:
export async function getStaticProps({ params }) {
const pageSlug = params.page ?? "homepage"
let pages = await fetchAPI(`/pages?slug=${pageSlug}`);
if(!pages || !pages.length > 0) {
pages = await fetchAPI(`/pages?slug=homepage`);
}
return {
props: { page: pages[0] },
revalidate: 1,
};
}