Adding Static Files to a Gatsby Site

Hero image for Adding Static Files to a Gatsby Site. Image by Belinda Fewings.
Hero image for 'Adding Static Files to a Gatsby Site.' Image by Belinda Fewings.

Wherever possible, it is preferable to use Gatsby itself for your website assets: these are then automatically optimised, minified, and renamed to include a cachebusting hash. However, there are inevitably situations where you do need to add static files to your site and don't want them to be processed by webpack or Gatsby.

In my experience, this is often for things like verification files from Google or Bing, or obscure icon formats or naming conventions which otherwise throw 404 errors in the server log. You can even use this to add backend functionality as an endpoint that you can then connect to via AJAX (for example: to power a contact form), add errorcapturing by adding PHP files here and then including them at buildtime (assuming your host supports this).

The answer could not be simpler: just put these files in the static folder in the root of your project. Some of the Gatsby starters do not include this by default, so you may need to create the folder first.

Anything within that static folder will be automatically copied across to the root of public onbuild. Any folders you have within static will also be copied across asis.

Not that you should ever do this, but if you then wanted to reference a static file from this folder within React, you would do so by starting with /.

render() {  return <img src={'/folder-inside-static/image.png'} alt="Lorem ipsum" />;}

Read more about using the static folder in the Gatsby documentation here.

Read more about Gatsby's overall project structure in the documentation here.


Categories:

  1. Development
  2. Front‑End Development
  3. Gatsby
  4. JavaScript
  5. Node.js