I am trying to wrap my head around Client-Side Rendering, Server-Side Rendering, and the behavior of the cache in the context of a Next.js App.
import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';
import { unstable_noStore as noStore } from 'next/cache';
export async function GET() {
//noStore();
try {
const result =
await sql`SELECT * FROM MESSAGES;`;
console.log(result);
return NextResponse.json({ result }, { status: 200, headers: { 'Cache-Control': 'no-store' } });
} catch (error) {
return NextResponse.json({ error }, { status: 500 });
}
}
Essentially, I have a client component (‘use client’) calling this above route handler that fetches a table from my database (postgres with Vercel).
The only way I have found to get the latest data (logged in result variable) is by using the noStore() function. I don’t understand why { ‘Cache-Control’: ‘no-store’ } doesn’t give me the latest data but instead data from hours or even days ago, even though my database is definitely up-to-date. Is it because the sql call is somehow cached by the server and { ‘Cache-Control’: ‘no-store’ } only disables storing in the server to client response ? While noStore() makes the whole scope of the function dynamic, hence disabling any form of caching ? I am also curious for any ressource explaining why the cached data might be stored for several days, or even weeks ?
Ramzi Belbahri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.