Cache JSON with a TTL

Hitting the same API or expensive sheet scan every trigger run burns quota. CacheService gives you a short-lived store (max ~6 hours) — perfect for rates, lookups, and memoized config.

What you'll need

  • A stable cache key string
  • A TTL in seconds (Apps Script caps at 21600)

How to use this snippet

function cacheGetJson(key) { var raw = CacheService.getScriptCache().get(key); if (raw == null) return null; return JSON.parse(raw); } function cachePutJson(key, value, ttlSeconds) { ttlSeconds = ttlSeconds || 600; CacheService.getScriptCache().put(key, JSON.stringify(value), ttlSeconds); } function getRatesCached() { var cached = cacheGetJson('fxRates'); if (cached) return cached; var rates = JSON.parse(UrlFetchApp.fetch('https://example.com/rates').getContentText()); cachePutJson('fxRates', rates, 300); return rates; }

Tips:

  • Cache is best-effort — it can be evicted early under memory pressure. Always treat a miss as normal.
  • Values must fit in ~100KB; for bigger blobs, store an ID and fetch from Drive/Sheet.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free themes and snippets — plus optional Co-Pilot when you want a boost (1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension