Skip to content

Offer function to invalidate cached function #2218

Closed

Description

@iBobik

Describe the feature

I some cases I will know cache is invalid.

const { call: getAccessToken, invalidate: invalidateAccessToken } = defineCachedFunction(async () => {
  const data = await fetch<any>('as/iam/authenticate', {

or

const getAccessToken = defineCachedFunction(async () => {
  const data = await fetch<any>('as/iam/authenticate', {
  …
}, {
  maxAge: 595,
  name: 'accessToken',
})


invalidateCachedFunction('accessToken')

Additional information

  • Would you be willing to help implement this feature?

Activity

  1. added
    pending triage
    on Mar 4, 2024
  2. adrienZ commented on Mar 5, 2024

    @adrienZ
  3. iBobik commented on Mar 5, 2024

    @iBobik
    ContributorAuthor
  4. atinux commented on Mar 6, 2024

    @atinux
    Member

    When using defineCahedFunction, Nitro will generate a specific key (learn more):

    `${options.group}:${options.name}:${options.getKey(...args)}.json`
    • Default of group is 'nitro:functions'
    • Default of name is '_'

    So if you have the following:

    const getAccessToken = defineCachedFunction(() => {
      return String(Date.now())
    }, {
      maxAge: 10,
      name: 'getAccessToken',
      getKey: () => 'default'
    })

    It will save in the storage the following key:

    nitro:functions:getAccessToken:default.json
    

    You can access the cache storage using:

    const cache = useStorage('cache')

    Then if you want to invalidate the cached function:

    const cache = useStorage('cache')
    await cache.removeItem('nitro:functions:getAccessToken:default.json')

    Hope that helps 😊

    I think a nice option would be to expose a .invalidate() method (or we can find a better name) for it.
    We could also expose some .meta() to know more about the cache options, key and next expiration.

    const getAccessToken = defineCachedFunction(() => {
      return String(Date.now())
    }, {
      maxAge: 10,
      name: 'getAccessToken',
      getKey: () => 'default'
    })
    
    // Get the meta
    await getAccessToken.meta()
    // Remove the entry in the cache storage
    await getAccessToken.invalidate()

    I think @pi0 may have some great ideas around it 💚

  5. added
    enhancement
    and removed
    pending triage
    on Mar 6, 2024
  6. IlyaSemenov commented on May 12, 2025

    @IlyaSemenov

    Another practical way would be:

    const getAccessToken = defineCachedFunction((param: string) => {
      return encode(param + String(Date.now()))
    }, {
      maxAge: 10,
    })
    
    await getAccessToken("foo") // cache miss
    await getAccessToken("foo") // cache hit
    await getAccessToken.withBypass("foo") // same as if shouldBypassCache() returned true
    await getAccessToken.withInvalidate("foo") // same as if shouldInvalidateCache() returned true

    I am using a wrapper for defineCachedFunction adding the above:

    import type { CacheOptions } from "nitropack/types"
    
    type CachedFunctionWithInvalidate<T, ArgsT extends unknown[] = any[]> = ((...args: ArgsT) => Promise<T>) & {
      withInvalidate(...args: ArgsT): Promise<T>
    }
    
    export function defineCachedFunctionWithInvalidate<T, ArgsT extends unknown[] = any[]>(fn: (...args: ArgsT) => T | Promise<T>, opts?: CacheOptions<T, ArgsT>) {
      let invalidated = false
    
      const cachedFunction = defineCachedFunction(fn, {
        ...opts,
        shouldInvalidateCache(...args) {
          if (invalidated) {
            invalidated = false
            return true
          }
          return opts?.shouldInvalidateCache ? opts.shouldInvalidateCache(...args) : false
        },
      }) as CachedFunctionWithInvalidate<T, ArgsT>
    
      cachedFunction.withInvalidate = (...args: ArgsT) => {
        invalidated = true
        return cachedFunction(...args)
      }
    
      return cachedFunction
    }

    then:

    const getAccessToken = defineCachedFunctionWithInvalidate((param: string) => { ... })
    
    await getAccessToken("foo") // normal use
    await getAccessToken.withInvalidate("foo") // force invalidate
  7. drewbaker commented on Feb 4, 2026

    @drewbaker

    I'm dealing with this today. Would like to expire/invalidate a cached function, such that the SWR=true is respected. Using removeItem('my_key') will remove the cache'd item altogether, not serve stale data.

    So it seems a invalidateItem('my_key') would be the expected function.

  8. pi0 commented on Mar 19, 2026

    @pi0
    Member

    This is now available in ocache (used by Nitro v3) via invalidateCache() and .invalidate() on cached functions:

    const getUser = defineCachedFunction(fetchUser, {
      name: "getUser",
      getKey: (id: string) => id,
    });
    
    // Invalidate a specific entry
    await getUser.invalidate("user-123");
    

    Or standalone when you don't have the function reference:

    import { invalidateCache } from "ocache";
    
    await invalidateCache({
      options: { name: "getUser", getKey: (id: string) => id },
      args: ["user-123"],
    });
    

    See unjs/ocache#8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions