Next.js Discord

Discord Forum

Nextjs 14 Caching Route Handlers

Answered
American black bear posted this in #help-forum
Open in Discord
Avatar
American black bearOP
I'm trying to implement PDF viewing in my app where I need to proxy PDF downloads through route handlers. The PDFs are accessed via download URLs, but I need to serve them for viewing in the browser. I'm experiencing a caching issue where the route handler makes a new request every time a dialog containing the PDF viewer is opened/closed.

my route.ts
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const pdfUrl = searchParams.get('url');
  if (!pdfUrl) {
    return new Response('PDF URL is required', { status: 400 });
  }
  try {
    const response = await fetch(pdfUrl);
    const pdfBuffer = await response.arrayBuffer();
    return new Response(pdfBuffer, {
      headers: {
        'Content-Type': 'application/pdf',
      },
    });
  } catch (error) {
    console.error('Error fetching PDF:', error);
    return new Response('Failed to fetch PDF', { status: 500 });
  }
}


some component
// This is wrapped in dialog component using shadcn
<div className="flex-1 overflow-auto">
    <Viewer
        fileUrl={`/api/getPdf?url=${encodeURIComponent(accessPdf)}`}
        plugins={[toolbarPluginInstance]}
    />
</div>
Answered by American black bear
Read the docs, I just had to add export const revalidate = 3600
View full answer

1 Reply

Avatar
American black bearOP
Read the docs, I just had to add export const revalidate = 3600
Answer