next.js: unstable_cache does not deserialize dates

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.5.0: Mon Apr 24 20:52:24 PDT 2023; root:xnu-8796.121.2~5/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.12.1
      npm: 9.6.4
      Yarn: 1.22.19
      pnpm: 7.13.1
    Relevant packages:
      next: 13.4.7-canary.2
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 4.9.5

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true), Data fetching (gS(S)P, getInitialProps)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/SSardorf/next_unstable_cache_date_deserialization

To Reproduce

  1. npm i
  2. npx prisma generate
  3. npx prisma db push
  4. npx prisma db seed
  5. npm run dev

When you first run the project, you’ll see that it loads correctly (cause first prisma invocation will result in non-cached data) When you refresh, the cached data will be shown, and it’ll throw an error, as post.createdAt is no longer a Date, but a string: <p>{post.createdAt.toISOString()}</p>

Describe the Bug

When you first run the project, you’ll see that it loads correctly (cause first prisma invocation will result in non-cached data) When you refresh, the cached data will be shown, and it’ll throw an error, as post.createdAt is no longer a Date, but a string: <p>{post.createdAt.toISOString()}</p>

Expected Behavior

unstable_cache should correctly de-serialize Dates.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 23
  • Comments: 25 (9 by maintainers)

Commits related to this issue

Most upvoted comments

here’s a typed version from @mordechaim’s solution:

import { unstable_cache } from "next/cache";
import { parse, stringify } from "superjson";

export const cache = <T, P extends unknown[]>(
  fn: (...params: P) => Promise<T>,
  keys: Parameters<typeof unstable_cache>[1],
  opts: Parameters<typeof unstable_cache>[2],
) => {
  const wrap = async (params: unknown[]): Promise<string> => {
    const result = await fn(...(params as P));
    return stringify(result);
  };

  const cachedFn = unstable_cache(wrap, keys, opts);

  return async (...params: P): Promise<T> => {
    const result = await cachedFn(params);
    return parse(result);
  };
};

I would like to point out that not only that it returns Date as string, it reports Typescript type as unchanged. Thus making the entire codebase using that data invalid since TS reports Date, but the data is actually string.

Yes, pretty straightforward.

Cache tags are done via cacheTag() function, which allows you to tag over the actual data! I don’t know if you realize how big of a deal this is.

You can do:

const getBlog = async (id: number) => {
    "use cache"

    const blog = await fetchMyBlog(id)
    cacheTag('blogs', `blog:${id}`, `blog:${blog.slug}`)

    return blog
}

revalidateTag and revalidatePath continue to work as expected.

Based on the suggestion from @numman-ali, here’s a utility you can use:

import { unstable_cache } from 'next/cache'
import superjson from 'superjson'

export const cache = (fn, keys, opts) => {
    const wrap = async (...params) => {
        const result = await fn(...params)
        return superjson.stringify(result)
    }

    const cachedFn = unstable_cache(wrap, keys, opts)

    return async (...params) => {
        const result = await cachedFn(...params)
        return superjson.parse(result)
    }
}

Be careful when using the custom cache solution mentioned above! unstable_cache by default uses the passed-in function’s definition and its arguments as the cache key. If this wrapper solution is used, then the function definition of wrap, which does not change, and any arguments passed to fn will be part of the cache key. Therefore, if you plan to use the cache solution for multiple cache entries, unique keyParts MUST be passed in, in order to differentiate the cache entries.

I’m embarrassed to say that I scratched my head for two days about why my cache was returning the wrong data, only to read into what unstable_cache was doing.

Please see this discussion thread for more info.

We can maybe improve the cache solution by always including fn.toString() as a key part (somebody check my work as I’m not a typescript person), which is what unstable_cache would do.

import { unstable_cache } from 'next/cache'
import { parse, stringify } from 'superjson'

type Callback = (...args: any[]) => Promise<any>

export function cache<T extends Callback>(
  fn: T,
  keyParts?: string[],
  opts?: { revalidate?: number | false; tags?: string[] }
): T {
  const wrap = async (params: Parameters<T>): Promise<string> => {
    const result = await fn(...params)
    return stringify(result)
  }

  return (async (...params: Parameters<T>) => {
    const keyPartsWithFn = [
      fn.toString(), // Use the function itself as part of the cache key
      ...(keyParts ?? []),
    ]
    const result = await unstable_cache(wrap, keyPartsWithFn, opts)(params)
    return parse(result)
  }) as T
}

I made the change today to transition from unstable_cache_safe to use cache. Was relatively painless and seems to be working well with dates too. Hopefully it also fixes my other cache inconsistency issue that was happening to me.

The new "use cache" directive will now be able to cache any RSC payload, including dates and many more.

Or just use this and call it a day…

Yes, pretty straightforward.

Cache tags are done via cacheTag() function, which allows you to tag over the actual data! I don’t know if you realize how big of a deal this is.

You can do:

const getBlog = async (id: number) => { “use cache”

const blog = await fetchMyBlog(id)
cacheTag('blogs', `blog:${id}`, `blog:${blog.slug}`)

return blog

} revalidateTag and revalidatePath continue to work as expected.

Had the same problem with dates, using the “use cache” functionality resolved the issue.

You can use the experimental.useCache flag which doesn’t require enabling dynamicIO

Was migrating between unstable_cache usages and use cache easy enough?

Not necessarily as to turn on the dynamicIO flag, its going to require you to remove export const dynamic = "force-dynamic"; from your pages if you use that.

Then theres the issue of https://nextjs.org/docs/messages/next-prerender-missing-suspense

So I gave up and I’ll wait for this stuff to be stable or better docs/migration path comes out.

I was surprised when I ran into this error. In my opinion this should be handled by next/cache itself without the need for extra code or dependencies.

The two solutions proposed above work well in the meantime as a workaround.

yep, just offering improved type declarations for unstable_cache as an alternative measure to improve type safety of the built-in serialization behavior and avoid unexpected runtime errors without having to add an external library