Querying all images in folder using GraphQL

You can select specific folders using filters in graphql.

Try something like this:

query AssetsPhotos {
  allFile(filter: {extension: {regex: "/(jpg)|(jpeg)|(png)/"}, relativeDirectory: {eq: "photos"}}) {
    edges {
      node {
        id
        name
      }
    }
  }
}

Where eq: photos should be changed to the relative directory result you get for the files you want to target when you go to GraphiQL and run a query on allFile.


I like to use sourceInstanceName when using gatsby-source-filesystem plugin as documented in the plugin docs.

Your gatsby-config.js

{
  resolve: "gatsby-source-filesystem",
  options: {
    path: `${__dirname}/content/legal`,
    name: "legal", // IMPORTANT: the name of your source instance
  },
}, {
  resolve: "gatsby-source-filesystem",
  options: {
    path: `${__dirname}/content/blog`,
    name: "blog",
  },
}

Then you can directly address them in your GraphQL query using filter and sourceInstanceName:

export const query = graphql`
{
  allFile(filter: {
      extension: {eq: "png"},
      sourceInstanceName: {eq: "blog"}
    })
  {
    edges {
      node {
      childImageSharp {
          fluid(maxWidth: 300, quality: 50) {
            originalName
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}

In contrast to relativeDirectory, this way you never have to deal with changing relative paths you might refactor your project or whatever. Just let GraphQL handle it for you!