DEV Community

Cover image for Handling Images in Gatsby with High Performance
William
William

Posted on

Handling Images in Gatsby with High Performance

Cloudinary is a cloud-based, end-to-end media-management platform on which you can store, dynamically optimize, and responsively deliver images and videos for both desktop or mobile apps.
The Gatsby-Source-Cloudinary plugin fetches optimized media assets from a folder on Cloudinary in a Gatsby project. Additionally:

  • You can declaratively query Cloudinary’s media assets alongside other application data with GraphQL.
  • Cloudinary delivers media assets through a content delivery network (CDN), reducing the app- bundle size on build.
  • Gatsby-Source-Cloudinary automatically optimizes the quality and format of the media files delivered by Cloudinary.

Thus, you have the best of two worlds: high-performance apps along with optimized delivery of media assets.
This tutorial steps you through the process of building a responsive image gallery with Gatsby and images from Cloudinary. Because Gatsby is written in React.js, you must have a working knowledge of JavaScript and React.js.

Installation of Node.js and Gatsby.js

You need Node.js and its package manager, npm, for this project. To check if they’ve been installed on your system, type the following command in your terminal:

    node -v && npm -v
Enter fullscreen mode Exit fullscreen mode

If the output show no version numbers, go to Nodejs.org to download and install Node.js, which ships with npm.
Next, install the Gatsby.js CLI tool by typing this command in your terminal:

    npm install -g gatsby-cli
Enter fullscreen mode Exit fullscreen mode

Creation of Cloudinary Account

To source images from Cloudinary, you must first set up an account there. Cloudinary offers a generous, free tier account that’s largely adequate for starter projects and that scales with the project.
Afterwards, do the following:

  1. Upload the images for the image gallery to a folder in your media library on Cloudinary. Name the folder with a name of your choice, e.g., gallery.
  2. Obtain your API key and API secret from your Cloudinary dashboard.

Creation of New Gatsby Project

Gatsby contains starters that quickly generate new projects with a base setup. To create a new Gatsby project in a folder of your choice with the default starter, type this command line:

    gatsby new cloudinary-site
Enter fullscreen mode Exit fullscreen mode

Next, navigate to the project directory and start a new development server on http://localhost:8000 with this command:

    cd cloudinary-site && gatsby develop
Enter fullscreen mode Exit fullscreen mode

Because it contains GraphQL, Gatsby simultaneously creates a GraphQL IDE on http://localhost:8000/___graphql, with which you will build GraphQL queries later.
Now go to http://localhost:8000 to see the new Gatsby project, which looks something like this:

New gatsby project

Installation of Additional Packages

You need two other packages for this project:

  • The dotenv module: for loading environment variables from a .env file.
  • The gatsby-source-cloudinary plugin: for fetching optimized images from Cloudinary.

Install them with npm by typing this command line:

    npm i --save dotenv gatsby-source-cloudinary
Enter fullscreen mode Exit fullscreen mode

Configuration of gatsby-config.js

You configure all plugins, including those that accompany the default starter, in the gatsby-config.js file, which resides in the root directory of Gatsby projects. Do the following:

  1. Import the dotenv file you installed earlier to the gatsby-confi.js file and add the gatsby-source-cloudinary plugin with this code:
    require('dotenv').config();

    module.exports = {
      ...
      plugins:[
      ...
      {
          resolve: `gatsby-source-cloudinary`,
          options: {
            cloudName: process.env.CLOUDINARY_CLOUD_NAME,
            apiKey: process.env.CLOUDINARY_API_KEY,
            apiSecret: process.env.CLOUDINARY_API_SECRET,
            resourceType: `image`,
            prefix: `gatsby-source-cloudinary/` 
          }
        }
      ]
    } 
Enter fullscreen mode Exit fullscreen mode

gatsby-source-cloudinary takes these options:

  • cloudName, apiKey , and apiSecret. These are credentials from your Cloudinary console, stored as three separate environment variables for security.
  • resourceType This is the resource type of the media assets: either an image or a video.
  • prefix This is the folder (in your Cloudinary account) in which the files reside. In the example above, I named this folder gatsby-source-cloudinary. Assign a name of your choice. Other optional options are type, tags, and maxResult.
  1. In the root of your project, create an environment file called .env to which to add your Cloudinary credentials and their values, like this:
    CLOUDINARY_API_KEY=xxxxxxxxxxxxxx
    CLOUDINARY_API_SECRET=xxxxxxxxxxxxxxxxxxxx
    CLOUDINARY_CLOUD_NAME=xxxxx
Enter fullscreen mode Exit fullscreen mode
The `dotenv` package exposes those environment variables in the project.
Enter fullscreen mode Exit fullscreen mode
  1. Restart the Gatsby development server to see the plugin in action, as in this example: Installation progress in console

Note the info log, which displays the CloudinaryMedia nodes. Those images are ready to be queried in Gatsby components.

Creation of Image Gallery

To create the image gallery:

  1. In the src/components folder, create a component file called ImageGallery.js and add the React functional component to the file, as follows:
    import React from 'react'
    import './gallery.css'
    import {useStaticQuery, graphql} from 'gatsby'
    const ImageGallery = () => {
        const data = useStaticQuery(graphql`query CloudinaryImage {
                allCloudinaryMedia {
                  edges {
                    node {
                      secure_url
                    }
                  }
                }
              }`
        )
        const clImages = data.allCloudinaryMedia.edges
        return (
            <div>
              <div className="image-grid">
                {clImages.map((image, index) => (
                      <div className="image-item" key={`${index}-cl`}>
                        <img src={image.node.secure_url} alt={"no alt :("} />
                      </div>
                    ))
                }
              </div>
            </div>
          )
      }
      export default ImageGallery
Enter fullscreen mode Exit fullscreen mode

Here, you query all the Cloudinary images sourced into the CloudinaryMedia nodes with the useStaticQuery hook. In turn, you map through those image URLs to create a gallery with the component.

  1. Create a file called ./gallery.css in src/components for styling the component. Add the CSS styles to the file, as follows:
    .image-grid {
        display: grid;
        grid-gap: 10px;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        grid-auto-rows: minmax(50px, auto);
      }
      .image-grid .image-item:nth-child(5n) {
        grid-column-end: span 2;
      }
      .image-grid img {
        display: flex;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
Enter fullscreen mode Exit fullscreen mode
The above styling renders your image gallery into a beautiful, responsive masonry grid.
Enter fullscreen mode Exit fullscreen mode
  1. Replace the existing content of the index.js file in the src/pages folder with the newly created ImageGallery component, as follows:
    import React from "react"
    import Layout from "../components/layout"
    import SEO from "../components/seo"
    import ImageGallery from "../components/ImageGallery"
    const IndexPage = () => (
      <Layout>
        <SEO title="Home" />
        <h1>Image Gallery</h1>
        <p>Here's a Gatsby site with optimized images in a masonry grid, served from <a href="https:cloudinary.com" target="_blank" rel="noopener noreferrer">Cloudinary</a></p>
        <div style={{ marginBottom: `1.45rem` }}>
          <ImageGallery/>
        </div>
      </Layout>
    )
    export default IndexPage
Enter fullscreen mode Exit fullscreen mode
Gatsby automatically creates dynamic routes for single pages in the  `src/pages` folder, with `index.js` being the root or home page.
Enter fullscreen mode Exit fullscreen mode
  1. Optional. Feel like tweaking the styles a bit? In the src/components/header.js file, change the background style property of the <header> element to #002954.

You might also like to rewrite the site title, which is pulled from the site metadata specified in gatsby-config.js. Update the title property of siteMetadata to Gatsby-Cloudinary Image Gallery.

Now restart the development server and have a look at the updated page. Here’s an example:

Image gallery from Cloudinary

Next, create a deployable, optimized build by typing this command in your terminal:

    gatsby build
Enter fullscreen mode Exit fullscreen mode

Deployment to Netlify

To deploy this JAMstack app to Netlify with a prebuilt continuous integration and continuous delivery (CI/CD) pipeline, follow these steps:

  1. Push your code to a remote repository, such as GitHub or Bitbucket.
  2. Create a Netlify account and log in.
  3. Create a new project from your deployed repository on Netlify.
  4. Type the build command and build directory in the text fields, in this case gatsby build and public, respectively. In most cases, Netlify detects the technology and auto-populates those fields.
  5. Add the environment variables to the environment variables settings on Netlify. Omitting this step will cause the deployment to fail.
  6. Run the deployment and voila! Your image gallery has taken shape.

Here’s the deployed version of this project.
And here’s the lighthouse audit of the deployed website, which showcases the power of Gatsby and Cloudinary with eight high-resolution images delivered on the page you just created:

Lighthouse performance scores

For the complete code, see its GitHub repository.

Summary

Now that you’ve learned how to build an optimized and responsive image masonry with the Gatsby-Source-Cloudinary plugin on Cloudinary, you can apply the process to other websites and apps on the JAMstack architecture.
Also, do check out the Gatsby-Transformer-Cloudinary plugin, with which you can upload media assets to Cloudinary and create file nodes off them, ready for use in the robust gatsby-image component in React. Have fun!

Top comments (0)