TIL: Add the "download" attribute on the link tag when calling the download endpoint
Downloading pdf or any other documents is very common in day-to-day web applications. We often see buttons like Download
, Generate Invoice
, etc buttons in web applications that makes calls to a GET
endpoint which does some computations and downloads pdf
or any other document file.
Problem
While working on one of the projects I added an endpoint
i.e. /generate-invoice
(GET) in a Phoenix
application. Its job was to do some tabular computation and generate a PDF. I added a link tag to call the endpoint something like this
<%= link "Invoice", to: "/generate-invoice", class: "button" %>
As expected it was working fine but later I noticed a weird behavior. After clicking the Invoice
button when I tried to click other buttons or any action that involved javascript, it wasn't working. I thought there was some bug with my endpoint or other code I tried to fix it but things weren't working for me.
Solution
When we try to access a GET
endpoint that downloads, the browser navigates away from the current page. It doesn‘t know the target will download something, and will therefore shut down the javascript of the current page. Till then I wasn't aware of the download
attribute on the link
tag. Adding the download
attribute on the above link tag helped me in fixing the problem.
<%= link "Invoice", to: "/generate-invoice", class: "button", download: 'invoice.pdf` %>
I hope you like this small TIL blog. If you have any questions please comment below. Thanks for reading 😊.
Subscribe to my newsletter
Read articles from AbulAsar S. directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
AbulAsar S.
AbulAsar S.
I am a Software Engineer from Mumbai, India. In love with Functional programming ( precisely Elixir). Love to share the knowledge that I learn while developing things.