TheEdoRan / next-safe-action

Type safe and validated Server Actions in your Next.js (App Router) project.
https://next.next-safe-action.dev
BSD 3-Clause "New" or "Revised" License
1.38k stars 26 forks source link

[BUG] Cache is skipped when using next-safe-action #85

Closed maatouk-j1 closed 2 months ago

maatouk-j1 commented 2 months ago

Are you using the latest version of this library?

Is there an existing issue for this?

Describe the bug

Next.js automatically caches fetch requests, but for some reason, when using next-safe-action, the fetch requests aren't being cached. I know that I can implicitly force the caching, but this shouldn't be the normal behavior.

I have the following code defined in my /lib/server-actions.ts file:

"use server";

import { createSafeActionClient } from "next-safe-action";

const action = createSafeActionClient();

type Post = {
  userId: number;
  id: number;
  title: string;
  body: string;
};

export const fetchPostsSafe = action({}, async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const data: Post[] = await res.json();
  return data;
});

As you can see this is a simple server action with no validations whatsoever.

I'm calling this action in my page.tsx file as follows:

import { fetchPostsSafe } from "@/lib/server-actions";

export default async function Page() {
  const { data: posts } = await fetchPostsSafe({});

  return (
    <div>
      <ul>
        {posts?.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

When accessing this page, I can see in the log that the cache is skipped:

GET https://jsonplaceholder.typicode.com/posts 200 in 450ms (cache: SKIP)
  │  │  Cache missed reason: (auto cache)

I tried using a regular Next.js server action instead the one created using next-safe-action, and the caching worked perfectly fine, I could see that the cache is indeed being hit.

Is this the normal behavior? or there's some kind of interference with the cache?

Reproduction steps

Mentioned above.

Expected behavior

The next safe action shouldn't skip the cache, it should act as a regular Next.js server action, which automatically caches fetch requests.

Reproduction example

N/A

Operating System

Windows 10

Library version

6.1.0

Additional context

No response

delete commented 2 months ago

Server actions should not cache the return value.

https://react.dev/reference/react/use-server#caveats