Handling Images in Gatsby with High Performance
Tags: react, gatsby, performance, webdev
Published: 2021-08-24 23:15:31

[Cloudinary](https://cloudinary.com) 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](https://github.com/Chuloo/gatsby-source-cloudinary) 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:

```bash
    node -v && npm -v
```

If the output show no version numbers, go to [Nodejs.org](https://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:

```bash
    npm install -g gatsby-cli
```

## Creation of Cloudinary Account

To source images from Cloudinary, you must first [set up](https://bit.ly/2v3sy4N) [an account](https://cloudinary.com/users/register/free) 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:

```bash
    gatsby new cloudinary-site
```

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

```bash
    cd cloudinary-site && gatsby develop
```

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](http://localhost:8000/) to see the new Gatsby project, which looks something like this:


![New gatsby project](https://paper-attachments.dropbox.com/s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579732344697_image.png)

## Installation of Additional Packages

You need two other packages for this project:

- The [dotenv](https://www.npmjs.com/package/dotenv) module: for loading environment variables from a `.env` file.
- The [gatsby-source-cloudinary](https://www.npmjs.com/package/gatsby-source-cloudinary) plugin: for fetching optimized images from Cloudinary.

Install them with npm by typing this command line:

```js
    npm i --save dotenv gatsby-source-cloudinary
```

## 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:

```js
    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/` 
          }
        }
      ]
    } 
```

`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`.


2. In the root of your project, create an environment file called `.env` to which to add your Cloudinary credentials and their values, like this:

```bash
    CLOUDINARY_API_KEY=xxxxxxxxxxxxxx
    CLOUDINARY_API_SECRET=xxxxxxxxxxxxxxxxxxxx
    CLOUDINARY_CLOUD_NAME=xxxxx
```    
    
    The `dotenv` package exposes those environment variables in the project.


3. Restart the Gatsby development server to see the plugin in action, as in this example:
![Installation progress in console](https://paper-attachments.dropbox.com/s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579734262094_image.png)

> 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:

```jsx
    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
```    
    
    

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.


2. Create a file called `./gallery.css` in `src/components` for styling the component. Add the CSS styles to the file, as follows:

```css
    .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;
      }
 ```   
    
    The above styling renders your image gallery into a beautiful, responsive masonry grid.



3. Replace the existing content of the `index.js` file in the `src/pages` folder with the newly created `ImageGallery` component, as follows:

```jsx
    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
```    
    
    Gatsby automatically creates dynamic routes for single pages in the  `src/pages` folder, with `index.js` being the root or home page.


4. **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](https://paper-attachments.dropbox.com/s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579735865260_gsc-sample.gif)


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

```bash
    gatsby build
```

## Deployment to Netlify

To deploy this JAMstack app to [Netlify](https://www.netlify.com/) 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](https://www.netlify.com/signup) 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](https://gsc-sample.netlify.com/) 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](https://paper-attachments.dropbox.com/s_F2DB697C20DB2900E952897A6582F157DAE4391AB0ADA1EBD0D8E2F67307CC1F_1579736874654_image.png)


For the complete code, see its [GitHub repository](https://github.com/Chuloo/gatsby-source-cloudinary-example).

## 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](https://www.npmjs.com/package/gatsby-transformer-cloudinary), 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!