User Agents

Web browsers and everyday web tech, explained

How to Cache Daily Reflection API Responses in Node.js

· 5 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to cache responses from a daily reflection API in a Node.js app. Caching reduces network latency, lowers API usage costs, and keeps your app responsive even if the upstream service is slow or down. You'll implement a simple in-memory cache with a time-to-live (TTL) that refreshes daily, plus a fallback to serve stale data if the API fails.

What You'll Need

  • A Node.js project (any version 14 or newer works).
  • An API endpoint that returns a daily reflection (e.g., a quote or meditation).
  • Basic familiarity with Express or plain Node.js HTTP.
  • No extra npm packages required—we'll use built-in modules.

Step-by-Step

  1. Set up your project structure. Create a folder and initialize it with npm init -y. If you don't have an entry file, create index.js.
  2. Define a cache object. At the top of your file, create a simple object to hold the cached data and a timestamp. For example:
    const cache = {
      data: null,
      fetchedAt: null
    };
    const TTL = 24 * 60 * 60 * 1000; // 24 hours in ms
    
  3. Create a function to fetch the reflection. This function calls your API using fetch (Node 18+ has global fetch) or https module. Return the parsed JSON.
  4. Implement the cache check. Write a function getReflection() that:
    • Checks if cache.data exists and if the current time minus cache.fetchedAt is less than TTL.
    • If yes, return the cached data immediately.
    • If no, fetch fresh data, store it in the cache, update fetchedAt, and return it.
  5. Add a stale-while-revalidate fallback. If the cache is expired but still has data, return the stale data immediately and trigger a background refresh. This keeps your app fast even if the API is slow.
  6. Handle API failures gracefully. If the fetch fails and you have cached data (even if stale), return that. Only throw an error if there's no cached data at all.
  7. Expose an endpoint. In Express, create a route like app.get('/reflection', async (req, res) => { ... }) that calls getReflection() and sends the result as JSON.
  8. Test your cache. Log the fetchedAt timestamp on each request. The first request should hit the API; subsequent ones within 24 hours should use the cache.
  9. Optionally, add a manual cache clear. Export a function that resets cache.data and cache.fetchedAt to null, useful for testing or admin endpoints.

Common Mistakes

  • Forgetting to update the timestamp after caching. If you don't set fetchedAt after a successful fetch, the cache will expire immediately on the next request.
  • Using a short TTL for a daily resource. If you set TTL to 1 hour, you'll hit the API 24 times a day instead of once. Make sure TTL matches your actual data freshness needs.
  • Not handling API errors. If the API is down and you have no cache, your app crashes. Always wrap the fetch in a try/catch and return a fallback or a 502 with a clear message.
  • Storing the cache in a global variable in a serverless environment. In AWS Lambda or similar, global state is not persistent across invocations. Use an external store like Redis or a file if you need persistence.

Tips

  • Use a module-level cache for simplicity. For a single-instance Node server, a simple object is fine. If you scale to multiple instances, consider a shared cache like Redis.
  • Add a Cache-Control header. When serving the response, set res.set('Cache-Control', 'public, max-age=86400') so CDNs and browsers can also cache it.
  • Log cache hits and misses. Add a simple counter or log line to monitor how effective your cache is.
  • Consider using a library like node-cache for more features. It provides TTL, keys, and stats out of the box, but for a single daily item, a plain object is enough.
  • Make TTL configurable via environment variable. This lets you adjust without code changes.

Troubleshooting

  • Cache never expires. Check that you're comparing Date.now() - cache.fetchedAt to TTL correctly. If fetchedAt is a string from JSON, convert it to a number with new Date(cache.fetchedAt).getTime().
  • API is called on every request. Verify that your condition uses < TTL, not <=. Also ensure that you're not clearing the cache accidentally in a middleware.
  • Stale data is never refreshed. If you implemented stale-while-revalidate, make sure the background refresh is not blocking the response. Use void refresh() or setTimeout to avoid awaiting it.
  • Memory leak due to cache. Since you only store one item, this is unlikely. But if you expand to multiple keys, use a Map and delete old entries.
  • App crashes when API is down. Ensure your catch block returns a 503 with a message like 'Service temporarily unavailable' and logs the error.

Frequently Asked Questions

Why not just use a library like node-cache?

You can, but for a single daily value, a plain object is simpler and has zero dependencies. Libraries add features like TTL and stats, which are useful if you have many keys.

How do I cache in a serverless environment?

Serverless functions are stateless, so an in-memory cache won't persist across invocations. Use a managed cache like Redis or a file in /tmp (which is ephemeral but may persist for a short time).

What if the API returns different data based on timezone?

Decide on a fixed timezone for your cache expiration. For example, set TTL to expire at midnight UTC. You can calculate the milliseconds until the next midnight and use that as TTL.

Can I cache the response in a database instead?

Yes, storing the cached JSON in a database (like MongoDB or Postgres) works, but adds latency. In-memory is fastest for a single instance.

How do I test the cache?

Use a tool like Postman or curl. Make a request, note the time, then make another request immediately. The second should return instantly and not hit the API. You can also add a console.log in your fetch function to see when it's called.

What if the daily reflection changes at a specific time?

You can schedule a refresh using setInterval or a cron job. For example, run a refresh at 00:00 UTC every day to pre-cache the new reflection.