Eric Nishio

Simple In-Memory Cache for Node.js


Here's a simple in-memory cache that you can use in a Node.js project. No external dependencies are required.

The only thing you need to do is provide an updater function that fetches the data and a TTL value for how long you want the data to be cached.

When you call the .read() method for the first time, it fetches and caches the data and returns it.

When calling .read() on cached data, it checks if the cache is still valid and returns the cached data. If the cache is outdated, it runs the updater function and refreshes the cache before returning the data.


interface Constructor<T> {
  update: () => Promise<T>
  ttl: number

class MemoryCache<T> {
  private state?: T
  private ttl: number
  private lastUpdatedAt: number
  private updater: () => Promise<T>

  constructor({ update, ttl }: Constructor<T>) {
    this.ttl = ttl
    this.lastUpdatedAt =
    this.updater = update

  private isOutdated = () => {
    return - this.lastUpdatedAt >= this.ttl

  update = async () => {
    try {
      this.state = await this.updater()
      this.lastUpdatedAt =
    } catch (e) {
      console.error('Failed to update cache:', e)

  read = async (): Promise<T | undefined> => {
    if (!this.state || this.isOutdated()) {
      await this.update()

    return this.state


const cache = new MemoryCache<MyData>({
  ttl: 3_600_000, // 1 hour
  update: async () => fetchData(),

Reading the cache

Japanese Wax Seal: NishioCopyright 2023 Eric Nishio