Displaying PDF file in Gatsbyjs

Viewed 1014

I am pretty new to Gatsbyjs and trying to build my portfolio for professional purpose. One issue though: when i try to link my pdf the address bar url adds some extra char. address bar

import resume from "../../static/samplepdf.pdf"

<li>
     <label htmlFor="resume">resume: </label>
            <a href={resume} target="_blank" rel="noreferrer" id="email">
              <FaNews className="social-icon"></FaNews>
              resume
            </a>
          </li>
2 Answers

As it has been said by @Quentin, this is the normal behavior when dealing with the static folder in Gatsby, the purpose of the hashed URL is to avoid the browser to cache old versions of the asset.

However, you can customize it a little bit the output using this approach:

<a href={`/samplepdf.pdf`} target="_blank" rel="noreferrer" id="email">
  <FaNews className="social-icon"></FaNews>
  resume
</a>

What will construct a URL like localhost:8000/samplepdf.pdf

Ah, so you're combining two approaches here.

  1. Importing the file uses Webpack to track the dependency. In this case, the file-loader will hash the file and copy it to your build output (in public), then return the path to the file (including the hash) as the import. So the resume variable here will be a string like /static/lalala.pdf.

  2. For files that you don't want processed via Webpack, Gatsby supports a static folder that will be copied to the build output without modification. In this case, your samplepdf.pdf file would be copied to public/static/samplepdf.pdf for you to reference on your site as /static/samplepdf.pdf. This file might end up with HTTP cache headers set that are irrespective of its contents, leading to stale cached versions. In your specific scenario I wouldn't be too worried about it, but this is something to be mindful of with resources that are embedded on the page (e.g. images, scripts, etc).

If you aren't concerned with the specific URL being used (and I wouldn't be, generally), I would go with the first approach. If you are linking to this file from another place on the web and need a consistent URL, go with the second approach. Or, if you want to use both approaches, you can likely continue as you are without causing any issues short of some confusion for you when you're working on this code in the future.

Related