← Back to all posts

đŸš«Before: magic numbers in code

When we write API requests and use caching, it’s tempting to just “drop” a number directly into the function:

export const fetchLivePages = unstable_cache(
  async () => {
    const response = await notion.dataSources.query({
      /* ... */
    });
    return response;
  },
  ["notion-pages"],
  {
    revalidate: 3600, // 1 hour
    tags: ["notion-posts"],
  }
);

export const fetchPageBySlug = (slug: string) =>
  unstable_cache(
    async () => {
      const response = await _fetchPageBySlug(slug);
      return response.results[0];
    },
    ["page-by-slug", slug],
    {
      revalidate: 300, // 5 minutes
      tags: [`post-${slug}`],
    }
  )();

At first glance it looks fine. But after a month you’ll forget what 300 or 3600 mean. And if you want to change your caching strategy, you’ll have to search for these numbers all over the project.

After: constants instead of hard‑coded values

It’s better to move these values into a separate file cacheConfig.ts

// lib/cacheConfig.ts
export const CACHE_TIMES = {
  LIVE_PAGES: 3600, // 1 hour
  PAGE_BY_SLUG: 300, // 5 minutes
};

export const CACHE_TAGS = {
  POSTS: "notion-posts",
  POST: (slug: string) => `post-${slug}`,
};

And then use them like this:

import { CACHE_TIMES, CACHE_TAGS } from "./cacheConfig";

export const fetchLivePages = unstable_cache(
  async () => {
    const response = await notion.dataSources.query({
      /* ... */
    });
    return response;
  },
  ["notion-pages"],
  {
    revalidate: CACHE_TIMES.LIVE_PAGES,
    tags: [CACHE_TAGS.POSTS],
  }
);

export const fetchPageBySlug = (slug: string) =>
  unstable_cache(
    async () => {
      const response = await _fetchPageBySlug(slug);
      return response.results[0];
    },
    ["page-by-slug", slug],
    {
      revalidate: CACHE_TIMES.PAGE_BY_SLUG,
      tags: [CACHE_TAGS.POST(slug)],
    }
  )();

Why this is cleaner

  • More clear: you immediately see that PAGE_BY_SLUG is the cache lifetime for a page.
  • Easier to change: if you want to increase TTL to 10 minutes, you change it in one place.
  • Fewer mistakes: you won’t mix up numbers or forget what they mean.
  • Self‑documenting code: constant names explain their purpose by themselves.