Description
I’m experiencing an issue with my Next.js (app Router) API routes deployed on Vercel. All API routes are being unexpectedly cached, despite multiple attempts to prevent caching. This is causing stale data to be served, even when the underlying data source (Strapi CMS) has been updated.
Steps to Reproduce
- Deploy a Next.js application with API routes to Vercel
- Set up API routes to fetch data from Strapi CMS
- Make changes to the data in Strapi CMS
- Fetch data from the API routes using a tool like Insomnia
Expected Behavior
The API routes should return the most up-to-date data from Strapi CMS.
Actual Behavior
The API routes are returning stale data that was present at build time. Changes made in Strapi CMS are not reflected in the API responses.
Code Example
Here’s an example of one of the affected API routes:
javascript
Copy
import { NextResponse } from "next/server";
import { gql } from "@apollo/client";
import { client } from "@/libs/apollo-client";
const GET_TWEETS = gql`
query GetTweets {
twitters(sort: "publishedAt:desc", pagination: { pageSize: 15 }) {
data {
id
attributes {
contenido
publishedAt
}
}
}
}
`;
export async function GET() {
try {
const { data } = await client.query({
query: GET_TWEETS,
fetchPolicy: "network-only",
});
const tweets = data.twitters.data.map((tweet) => ({
id: tweet.id,
contenido: tweet.attributes.contenido,
publishedAt: tweet.attributes.publishedAt,
}));
console.log(
data.twitters.data[0].attributes.contenido,
tweets[0].contenido
);
return new Response(JSON.stringify(tweets), {
status: 200,
headers: {
"Cache-Control": "max-age=10",
"CDN-Cache-Control": "max-age=60",
"Vercel-CDN-Cache-Control": "max-age=3600",
},
});
} catch (error) {
console.error("Error:", error);
const errorResponse = NextResponse.json(
{ error: "Error al obtener los tweets" },
{ status: 500 }
);
errorResponse.headers.set("Cache-Control", "no-store, max-age=0");
return errorResponse;
}
}
export const dynamic = "force-dynamic";
Attempted Solutions
- Using
export const dynamic = "force-dynamic";
- Setting various
Cache-Control
headers - Using
fetchPolicy: "network-only"
in Apollo Client - Checking responses with Insomnia to confirm the issue
None of these solutions have resolved the caching problem.
This issue is affecting all API routes in the application, not just the example provided. It’s critical for our application to always serve the most recent data from Strapi CMS.
Any assistance in resolving this unexpected caching behavior would be greatly appreciated.