How can I initiate a file download when a button is clicked?
During testing, I noticed that sending a GET request using
<Link href="/api/generate-pdf">
works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the download does not start.
This is how my button looks in a Next.js 13 Client Component:
function generatePdf() {
fetch("/api/generate-pdf", {
method: "POST",
headers: {
"Content-type": "application/pdf",
},
body: JSON.stringify(store),
})
}
<Button onClick={generatePdf} type="button">
Generate PDF
</Button>
API Route Handler:
export async function POST(request: Request) {
console.log("/api/generate-pdf POST Request")
try {
// ...
// generate the pdf file
const generatedPdf = doc.output("blob")
const filename = "pac.pdf"
const res = new Response(generatedPdf, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"content-disposition": `attachment; filename="${filename}"`,
},
})
return res
} catch (error) {
console.log(error)
return NextResponse.json("Internal Error", { status: 500 })
}
}