#Cache post request

1 messages · Page 1 of 1 (latest)

plucky merlin
#

I am trying to make a view counter which saves the ip once per day

"use server";
import { ArticleSchemaType } from "@/validations/types";

export async function AddView(
  articleData: ArticleSchemaType,
  userIP: string | null
) {
 
  if (!userIP) return;
  const view = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/view`, {
    method: "POST",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Authorization: `users API-Key ${process.env.API_KEY}`,
    },
    body: JSON.stringify({
      ip: userIP,
      article: articleData.id,
      timestamp: new Date().toISOString(),
    }),
    cache: "force-cache",
    next: {
      //1 day
      revalidate: 86400,
    },
  });
  console.log(view);
}

Why is it that everytime i do a refresh, a new view is added in the backend? I have the cache headers set correctly

static valeBOT
#

Hi @plucky merlin. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, it seems that your POST request is being cached by Next.js. However, the caching behavior of POST requests in Next.js can be influenced by several factors.

According to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data), fetch requests that use the POST method are automatically cached, unless they are inside a Route Handler that uses the POST method.

However, there are exceptions to this rule. As mentioned in the Github issue (https://github.com/vercel/next.js/issues/52405), requests are not cached if dynamic methods are used and the fetch is a POST request or uses Authorization or cookie headers.

In your case, you are using an Authorization header in your POST request, which according to the documentation, should opt the fetch out of caching. However, there seems to be some confusion and potential issues around this behavior as discussed in the Github issue.

As a workaround, you might want to consider using the revalidatePath or revalidateTag functions as mentioned in the Vercel documentation (https://vercel.com/docs/edge-network/caching). These functions can be used to trigger revalidation of cached data.

If you continue to face issues, it might be a good idea to raise a new issue in the Next.js Github repository, providing all the relevant details and code snippets. The Next.js team and community can then help you troubleshoot the issue further.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@plucky merlin kapa.ai is still learning and improving, please let us know how it did by reacting below

plucky merlin
#

@static vale i want to cache the post request so the backend only gets 1 request per day, but that isnt happening and the backend keeps getting requests to add a view

static valeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the information provided in the extracts, it seems that the POST request is not being cached as expected due to the use of the Authorization header. According to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching), fetch requests are not cached if the fetch request uses Authorization headers.

This behavior is also discussed in a Github issue (https://github.com/vercel/next.js/issues/52069), where it's mentioned that POST requests are cached, but not deduplicated, which can be confusing.

As a workaround, you might want to consider using a different method for authorization that doesn't involve the Authorization header, or find a way to cache the data on the client-side and only send a POST request when necessary.

If you continue to face issues, it might be a good idea to raise a new issue in the Next.js Github repository, providing all the relevant details and code snippets. The Next.js team and community can then help you troubleshoot the issue further.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@plucky merlin kapa.ai is still learning and improving, please let us know how it did by reacting below

plucky merlin
#

@static vale

"use server";
import { ArticleSchemaType } from "@/validations/types";

export async function AddView(
  articleData: ArticleSchemaType,
  userIP: string | null
) {
  if (!userIP) return;
  const view = await fetch(`${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/view`, {
    method: "POST",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      ip: userIP,
      article: articleData.id,
      timestamp: new Date().toISOString(),
    }),

    next: {
      //1 day
      revalidate: 86400,
    },
  });
}

will this server action be cached or not?

static valeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the information provided in the extracts, it seems that the POST request in your server action may not be cached as expected.

According to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/caching#data-cache), fetch requests are cached by default. However, this behavior can be influenced by several factors.

In a Github issue (https://github.com/vercel/next.js/issues/51138), it's mentioned that Server Actions are not executed under the React rendering context, and React APIs like cache won’t work inside. Instead, you can use any server cache mechanism like Map or LRU.

Also, the next option with revalidate that you're using in your fetch request is not a standard option for the Fetch API and it's not mentioned in the provided extracts from the Next.js documentation. It's unclear how this option would affect the caching behavior of the fetch request.

If you want to ensure that the POST request is only made once per day, you might need to implement a different caching mechanism on the server-side or client-side. If you continue to face issues, it might be a good idea to raise a new issue in the Next.js Github repository, providing all the relevant details and code snippets. The Next.js team and community can then help you troubleshoot the issue further.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: