How to correctly convert a static page into an "expired page"?
P粉930448030
P粉930448030 2023-09-11 19:35:30
0
1
541

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粉930448030
P粉930448030

reply all(1)
P粉144705065

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!