Reputation: 1089
I'm using NextJS 14.x, and have a simple /dashboard/page.tsx where I fetch data from an API. I would expect that when I change the message data I would be getting the updated response. Even if I am fetching data from a remote URL (different server) the data still appears to be cached by NextJS which makes fetching data that changes impossible.
async function fetchdetails() {
const response = await fetch(
"http://localhost:3000/api/public"
);
if (response.ok) {
const responseBody = await response.json();
console.log(responseBody);
return responseBody;
}
}
The API is under the /api/public folder (route.ts)
const data = {
"message": "hello world!"
}
export async function GET() {
return NextResponse.json(data)
}
What is the right strategy to make sure the data is never cached by the app?
Upvotes: 2
Views: 3543
Reputation: 11
By default, NextJs always cache GET method. If you want opt-out caching, your API route need to use one of below:
const data = {
"message": "hello world!" }
export async function GET(request: Request) {
return NextResponse.json(data)
}
const data = {
"message": "hello world!" }
export const dynamic = 'force-dynamic'
export async function GET() {
return NextResponse.json(data)
}
If you want more granular caching strategy, you can put { cache: 'no-store' }
in fetch
, read more Caching in Next.js.
Upvotes: 1
Reputation: 1089
I'm not sure if this is the most efficient way (versus a config) but adding noStore() to the fetch method did work.
import { unstable_noStore as noStore } from 'next/cache';
async function fetchdetails() {
noStore();
const response = await fetch(
"http://localhost:3000/api/public"
);
if (response.ok) {
const responseBody = await response.json();
console.log(responseBody);
return responseBody;
}
}
Upvotes: 3