Skip to content

Instantly share code, notes, and snippets.

@mdarens
Last active July 7, 2021 21:39
Show Gist options
  • Save mdarens/bf41586b18c054207606c7672a3d05ca to your computer and use it in GitHub Desktop.
Save mdarens/bf41586b18c054207606c7672a3d05ca to your computer and use it in GitHub Desktop.
Next.js revalidation strategy for routes associated with dates
import { differenceInCalendarDays } from "date-fns";
const buildDate = new Date();
// starting at 1 minute, add a minute to the revalidation
// for each additional day in the past/future.
// for example, a page associated with a date today, tomorrow or yesterday would refetch when stale by a minute.
// one a week in the past or future would only revalidate every 7 minutes,
// and one a month out would revalidate on the half hour.
// the assumption here is that events, posts and other entities with
// times attached to them are modified more frequently near to the time in question.
// top out at 2 hours.
export default function getRevalidationStrategyByDay(
year: string,
month: string,
dayOfMonth: string
) {
const distance = Math.abs(
differenceInCalendarDays(
buildDate,
new Date(
Number.parseInt(year, 10),
Number.parseInt(month, 10) - 1,
Number.parseInt(dayOfMonth, 10)
)
)
);
const revalidate = Math.min(7200, Math.max(1, distance) * 60);
return revalidate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment