I have a bunch of static promotion pages. However, if the promotion has expired, I need to navigate/display an expiration page. What's the correct way to do this in a static page with NextJS?
Attempt 1: Check whether it is expired in getStaticProps. The problem is, revalidation happens every 600 seconds. So this might happen at 12:28 AM instead of the exact 12:00 (depending on when I deploy it).
So it doesn't display the expired page on time. how to solve this problem? Or implement the "correct" way to change pages.
export const getStaticPaths = async () => { const pageSlugs = await api.getAllSlugs(); const paths = pageSlugs.map((slug) => (params: {promo: slug}) ); return { paths, fallback: "blocking" }; }; export async function getStaticProps({ preview = false, params, previewData }) { const page = await api.getSlug(params.promo, { preview, enviroment: previewData?.enviroment }); const isExpired = checkIfExpired(page.promoStart, page.promoEnd); const expiredPage = isExpired ? await api.getPage("expired-page", { preview, enviroment: previewData?.enviroment }) : null; return { props: { page, isExpired, expiredPage, }, revalidate: 600 }; }
P粉1447050652023-09-12 16:57:12
You can dynamically calculate the revalidation time:
export async function getStaticProps({ preview = false, params, previewData }) { const page = await api.getSlug(params.promo, { preview, enviroment: previewData?.enviroment }); const isExpired = checkIfExpired(page.promoStart, page.promoEnd); const expiredPage = isExpired ? await api.getPage("expired-page", { preview, enviroment: previewData?.enviroment }) : null; let revalidate = 600 if (Date.now() <= page.promoStart) { revalidate = (page.promoStart - Date.now()) / 1000 } else if (date.now() > page.promoStart && Date.now() <= page.promoEnd) { revalidate = (page.promoEnd - Date.now()) / 1000 } return { props: { page, isExpired, expiredPage, }, revalidate }; }
This assumes promoEnd
and promoStart
are date objects, but you can adjust this if needed. Also make sure the server time is aligned with the time zone used by the date object.