Loading file list in Next.js does not reflect the latest changes

In Next.js, I implemented a feature to fetch a list of files in a specific directory using a module like fs.

When I deployed it, the functionality itself worked fine, but when I took actions such as uploading or deleting new files to that directory and then re-entered the website, it didn’t reflect those changes at all. (For example, if I added a file called test.txt to the directory and then re-entered the website, it didn’t reflect the latest changes).

After rebuilding by running the npm run build command, I was able to see that the changes were reflected.

Below is the code for /lab/page.js.

const fetchFiles = async () => {
    try {
      console.log('Fetching files...');
      const res = await fetch('/api/files/lab', {
        credentials: 'include'
      });
      if (!res.ok) {
        throw new Error(`Error: ${res.status} ${res.statusText}`);
      }
      const data = await res.json();
      console.log('Files fetched successfully:', data.files);
      setFiles(data.files);
    } catch (error) {
      console.error('Failed to fetch files:', error);
      setError(error.message);
    }
  };

And below is the code for /api/files/lab/route.js. This is the API to get the list of files.

import { NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';

export async function GET() {
  const directoryPath = '*MY_DIRECTORY*';
  try {
    const files = await fs.readdir(directoryPath);
    const fileDetails = await Promise.all(files.map(async (file) => {
      const filePath = path.join(directoryPath, file);
      const stats = await fs.stat(filePath);
      return {
        name: file,
        uploadDate: stats.mtime.toISOString(),
        path: `/api/files/lab/download?file=${encodeURIComponent(file)}`,
      };
    }));
    return NextResponse.json({ files: fileDetails });
  } catch (error) {
    console.error('Error reading directory:', error);
    return NextResponse.json({ error: 'Failed to read directory' }, { status: 500 });
  }
}

I’ve identified the problem as being caused by changes not being reflected in static builds, but I haven’t found a solution yet.