Next.js Discord

Discord Forum

Disabling SQL Cache // Stale data from vercel/postgres sql

Unanswered
Goldstripe sardinella posted this in #help-forum
Open in Discord
Goldstripe sardinellaOP
Hey 👋

So I've coded myself into a little bit of a corner here. Please mind: This is my first app project with next.js so please feel free to point out rookie mistakes!

I've got a route.ts that is supposed to fetch all entries of a database table, cram them into a CSV and download it to the requesting user's computer. To get all the data, it uses a findAll method, i've written using the versel/postgres SQL client.

However it returns stale data. I've tried disabling the cache since vercel sql uses fetch under the hood and all fetch requests are cached by default.

I've tried accomplishing this using export const dynamic = 'force-dynamic'; but that didn't do the trick. Directly exporting this from the file where the findAll lives doesn't work, since it's a 'use server' component: Either next complains only async constants can be exported here or - if i remove 'use server' - it can't find the DB-credentials from env.

So I'm in a bit of a bind here.

Can someone give me tipps to refactor this?

Cheers,
Max

PS: Wil post my code in the comments to mitigate discord post limit

1 Reply

Goldstripe sardinellaOP
### findAll() Method to get all DB entries
'use server'

import { sql } from "@vercel/postgres";

export const findAll = async () => {
    const data = await sql`
      SELECT * FROM studyruns
    `;
    return data.rows;
}



### Route to Download CSV

js 
import { findAll } from "@/_services/studyruns";
import { json2csv } from 'json-2-csv';

export const dynamic = 'force-dynamic';

export async function GET(request: Request) {
  try {
    const studyruns = await findAll(); // Fetch all studyruns from the database
    const csv = json2csv(studyruns); // Use json2csvAsync to convert JSON to CSV

    return new Response(csv, {
      headers: {
        'Content-Type': 'text/csv',
        'Content-Disposition': 'attachment; filename="studyruns.csv"',
        'Cache-Control': 'no-store' // Disable caching
      },
    });
  } catch (error) {
    console.error('Error generating CSV:', error);
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    return new Response(JSON.stringify({ error: errorMessage }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}