title: How to download a file on Next.js using an API route
body: <p>I'm using next.js. I have a 3rd party service I need to retrieve a PDF file from. The service requires an API key that I don't want exposed on the client side.</p>
  <p>Here are my files</p>
  <p>/api/getPDFFile.js
  ...</p>
  <pre><code>  const options = {
      method: 'GET',
      encoding: 'binary',
      headers: {
        'Subscription-Key': process.env.GUIDE_STAR_CHARITY_CHECK_API_PDF_KEY,
        'Content-Type': 'application/json',
      },
      rejectUnauthorized: false,
    };
  
    const binaryStream = await fetch(
      'https://apidata.guidestar.org/charitycheckpdf/v1/pdf/26-4775012',
      options
    );
    
    return res.status(200).send({body: { data: binaryStream}}); 
  
  
  </code></pre>
  <p>pages/getPDF.js</p>
  <pre><code>   &lt;button type=&quot;button&quot; onClick={() =&gt; {
    fetch('http://localhost:3000/api/guidestar/charitycheckpdf',
      {
        method: 'GET',
        encoding: 'binary',
        responseType: 'blob',
      }).then(response =&gt; {
        if (response.status !== 200) {
          throw new Error('Sorry, I could not find that file.');
        }
        return response.blob();
      }).then(blob =&gt; {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.setAttribute('download', 'test.pdf');
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      })}}&gt;Click to Download&lt;/button&gt;
  </code></pre>
  <p>Clicking the button downloads a file, but when I open it I see the error message, &quot;Failed to load PDF document.&quot;</p>