Last active
July 7, 2021 21:39
-
-
Save mdarens/bf41586b18c054207606c7672a3d05ca to your computer and use it in GitHub Desktop.
Next.js revalidation strategy for routes associated with dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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