Next.js

Lesson 08

Caching and revalidation intent

Make caching choices explicit so freshness and performance match the product need.

Good Code

lib/posts.ts
import { cacheLife, cacheTag } from "next/cache";

export async function getPublishedPosts() {
  "use cache";
  cacheLife("hours");
  cacheTag("posts");

  // The cache directive, lifetime, and tag make freshness explicit.
  return db.post.findMany({
    where: { published: true },
    orderBy: { publishedAt: "desc" },
  });
}

Bad Code

lib/posts.ts
export async function getPublishedPosts() {
  // This fetch has no stated freshness or revalidation policy.
  const response = await fetch("https://cms.example.com/posts");

  return response.json();
}

Review Notes

What to review

Good Code

The good version states that published posts can be cached for hours and tagged for targeted revalidation.

Bad Code

The bad version relies on an unstated assumption that framework fetches are cached, which is not true by default in this Next.js version.

Takeaways

  • Cache data with an explicit lifetime or tag when shared content can be reused.