Menu

Cache Lifetimes and Invalidation

Lesson 3: Cache Lifetimes and Invalidation

How long should data be cached?

cacheLife sets three timings for a cached function:

Property Meaning
stale How long the browser may reuse the data without asking the server
revalidate After this, the next request triggers a background refresh
expire After this with no traffic, the next request waits for fresh data

Built-in profiles:

Profile Typical content stale revalidate expire
default Standard content 5 min 15 min Never
seconds Live scores, prices 30 s 1 s 1 min
minutes Feeds, news 5 min 1 min 1 hour
hours Inventory, catalogues 5 min 1 hour 1 day
days Blog posts, course pages 5 min 1 day 1 week
weeks Newsletters, podcasts 5 min 1 week 30 days
max Legal pages, archives 5 min 30 days 1 year

Source: Next.js cacheLife reference

Example

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

export async function getCourse(slug: string) {
  'use cache';
  cacheLife('days');
  cacheTag('courses', `course-${slug}`);

  return db.course.findUnique({ where: { slug } });
}

When an instructor edits a course, invalidate just that entry:

'use server';
import { updateTag } from 'next/cache';

export async function saveCourse(slug: string, formData: FormData) {
  await db.course.update({ where: { slug }, data: parseCourse(formData) });
  updateTag(`course-${slug}`);
}

When a CMS sends a webhook, refresh in the background:

// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';

export async function POST(request: Request) {
  if (request.headers.get('x-webhook-secret') !== process.env.WEBHOOK_SECRET) {
    return Response.json({ error: 'Unauthorised' }, { status: 401 });
  }
  const { slug } = await request.json();
  revalidateTag(`course-${slug}`, 'max');
  return Response.json({ revalidated: true });
}

How it works

  • Time-based: cacheLife('days') refreshes the entry automatically once a day.
  • On-demand: cacheTag labels entries; updateTag or revalidateTag expires every entry with that label.
  • Use both together: a long lifetime for speed, plus tags so edits appear immediately.
  • Custom profiles, such as editorial, can be defined under cacheLife in next.config.ts.

Common mistakes

Mistake Effect Fix
No cacheLife call Lifetime silently falls back to default Set a profile in every 'use cache' scope
Only time-based expiry for editable content Edits take hours to appear Add cacheTag and invalidate on save
Unprotected revalidation endpoint Anyone can flush your cache Check a secret or signature
Very short lifetimes everywhere Cache adds overhead with little benefit Leave truly live data uncached in Suspense

Key takeaways

  • cacheLife = how long; cacheTag = what to invalidate later.
  • Pair long lifetimes with tag-based invalidation for fast and fresh content.

Try it: Tag each course with course-<slug>, give it a days lifetime, and invalidate it from the edit-course action.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details