In my Next.js 13 project, I'm working on implementing dynamic routes where the server initially calls an API when a page is first visited.
If the corresponding data entry exists, I want the server to generate the HTML page so that it's ready for subsequent visits without regeneration.
However, if the data entry doesn't exist, I'd like to redirect the visitor to a 404 page.
Here is how I used to achieve this in Next.js 12:
export const getStaticPaths = async () => ({
paths: [], //generating all pages on-demand
fallback: true,
});
export async function getStaticProps(context) {
try {
const { id } = context.params; // Getting the id from the URL
const ArticleData = await ArticleApi(id); // API call
return {
props: {
ArticleData: ArticleData.data, // Sending the data returned by the API to the page
},
};
} catch (error) {
// if an error occured on api call
return {
notFound: true, // Redirect to 404
};
}
}
export default function Article({
ArticleData,
}) {
if (!ArticleData) return <div>Loading...</div>; // While the server is making the API call
return (<>page code </>)
}