Next.js Discord

Discord Forum

Using revalidateTag in Post Request doesn't trigger the fetch again.

Unanswered
Drokoz posted this in #help-forum
Open in Discord
Hi everyone! Im trying to do some revalidation of conversations and messages, the idea is to use parallel routing for a modal between insights of a clienta and the chat with the client. Im doing the fetch request in the page.tsx of the chat, but when i tried to revalidateTag the request via a PostRequest doesn't trigger it.
What i understand for cache rendering is that the called should be in a Server Action called by a server component/page. Also the only way to call a revalidateTag should be in a Request or a Server Action. So that's why im using parallel routing, if not the nesting via client/component doesn't work for this case.
The photo atached is my route app. I would pass my files via comments. Thanks to everyone in advanced!!! 😃
This is my page.tsx for the chat:
import Link from "next/link";
import {
  fetchConversationByParticipantId,
  fetchConversationMessages,
} from "@/components/(campaigns)/messages/actions";
import ChatUI from "@/components/(campaigns)/messages/components/ChatUi";
import { MessagesResponse } from "@/interface/interfaces";

export default async function ParticipantChat({
  params,
}: {
  params: { idCampaign: string; participantId: string };
}) {
  // Fetch conversation data for the participant
  console.log("Fetching conversation data for the participant...");
  const conversation = await fetchConversationByParticipantId(
    Number(params.participantId)
  );
  console.log("Conversation data fetched successfully.", conversation);

  if (!conversation) {
    console.log("No conversation found for this participant.");
    return (
      <div className="p-4 text-red-500">
        No conversation found for this participant.
      </div>
    );
  }

  const messages: MessagesResponse = await fetchConversationMessages({
    id_conversation: conversation.id_conversation,
  });
  console.log("Conversation messages fetched successfully.", messages);

  return <ChatUI messages={messages} conversation={conversation} />;
}

3 Replies

This is the action called for the fetch:
export const fetchConversationMessages = async (data: {
  id_conversation: number;
}) => {
  const url = `${process.env.NEXT_PUBLIC_BACKEND_URL}/messages/conversation/${data.id_conversation}`;

  console.log("[DEBUG] Fetching data from URL:", url);

  const res = await fetch(url, {
    next: {
      revalidate: 0, // Reduce el tiempo si necesitas datos inmediatos
      tags: [`messages-${data.id_conversation}`], // Invalida mensajes específicos
    },
    headers: {
      "Content-Type": "application/json",
    },
  });

  if (!res.ok) {
    throw new Error(`Failed to fetch messages: ${res.statusText}`);
  }

  return res.json() as Promise<MessagesResponse>;
};


This is my post request on route.ts
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    console.log("[WEBHOOK] Received payload:", body);

    if (!body || !body.conversationId) {
      return NextResponse.json(
        { error: "Invalid payload: conversationId is required." },
        { status: 400, headers: { "Cache-Control": "no-cache" } }
      );
    }

    const { conversationId } = body;
    console.log(
      `[WEBHOOK] Triggering revalidation for conversationId: ${conversationId}`
    );

    // Call the server action for revalidation
    revalidateTag(`messages-${conversationId}`); // Revalida el tag de la conversación específica

    console.log("[WEBHOOK] Revalidation complete.");
    return NextResponse.json(
      { success: true },
      { headers: { "Cache-Control": "no-cache" } }
    );
  } catch (error) {
    console.error("[WEBHOOK] Error processing webhook:", error);
    return NextResponse.json(
      { error: "Internal server error." },
      { status: 500, headers: { "Cache-Control": "no-cache" } }
    );
  }
}
My ChatUi component
Does anyone know something? And anyone see this can you explain me how to ask question in incredible but always that i tried to ask something in a forum i never get any answers haha