Next.js Discord

Discord Forum

invalidate cache at a specific time

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
i woulld like to invalidate cache at midnight, can i pass in say a default arg as a date?

eg

import { cacheLife, cacheTag } from "next/cache";

function getDayKeyUtc() {
  const now = new Date();

  const y = now.getUTCFullYear();
  const m = String(now.getUTCMonth())
  const d = String(now.getUTCDate())
  
  return `${y}-${m}-${d}`;
}

export async function getBanner(
  page: Banner['pages'][number],
  dayBucket = getDayKeyUtc()
) {
  'use cache';

  // Used only to rotate the cache key once per UTC day.
  void dayBucket;

  // Old daily cache entries should be ejected after 1 day.
  cacheLife({
    stale: 86400,
    revalidate: 86400,
    expire: 86400,
  });

  cacheTag(getCacheKey(page));

  // ...
}

would this work? (we use cache life as we're using keys to properly invalidate the prior one - or would i need to get date before and use tags to invalidate the prior days?)

0 Replies