What is the best way to make my Gatsby rig pull in images from S3?

Viewed 560

I am trying to incorporate ai2html into a Gatsby-built repo. I realized quickly that I cannot simply used gatsby-image because I am not deploying everything to one place: my code, via public/index.html, goes to one place and my images live in AWS S3. I'm looking for a way to pull images via URL into my src/index.js, ideally in a step-by-step tutorial way because I am new at Gatsby stuff.

So far, I've tried using gatsby-source-s3 (docs here) but I'm not sure I've set it up correctly in my index.js (I've already installed it and put the relevant info in gatsby-config.js:

import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import "../styles/ai_styles.css"

export default () => {

const data = useStaticQuery(graphql`
  query IndexQuery {
    images: allS3Images {
      edges {
        node {
          Key
          Url
        }
      }
    }
  }
`)

return (

<div>

<div id="g-crime-box" className="ai2html ai2html-box-v5">
        <div id="g-mobile" className="g-artboard" style={{width: '280px', height: '2328.3424680476px'}} data-aspect-ratio="0.12" data-min-width="280" data-max-width="579">
          <Img fluid={data.images.node.Url} alt="alt desktop image" />

...

</div>

My main questions are, is {data.images.node.Url} the best way to call the image or am I doing that wrong? And is this the best way to do this? Has anyone seen other ways to do this?

1 Answers

You're right that you should pull images from S3 at build time, and that using a community plugin for this –like gatsby-source-s3– will make your life easier.

Right now, though, you're using the AWS object URL directly in your source, so images will basically be downloaded directly from your bucket, unprocessed, by your users.

What you probably want is to download the image into a local node (this is handled by Gatsby's sourceNodes API) to process with sharp.

To do this, you'll need to change your GraphQL query to use childImageSharp on your S3 nodes. gatsby-source-s3 has an example of this on its README:

query IndexQuery {
  images: allS3Image {
    edges {
      node {
        file: localFile {
          image: childImageSharp {
            sizes(maxWidth: 400, maxHeight: 400) {
              ...GatsbyImageSharpSizes_withWebp_tracedSVG
            }
          }
        }
      }
    }
  }
}

Last but not least...

(Disclaimer: I'm the author of a plugin mentioned below.)

The gatsby-source-s3 plugin looks unmaintained, so you might run into issues with it.

For that reason, I built another S3 source plugin for my Gatsby sites, and published it here:

@robinmetral/gatsby-source-s3

The README has extensive documentation, including a section on processing images with sharp, that you might find useful.

Related