Upload Images To Cloudinary in Gatsby.Js Projects

Upload Images To Cloudinary in Gatsby.Js Projects

Outline:

  1. Introduction
  2. Prerequisites
  3. Getting Cloudinary API key
  4. Creating a GatsbyJS Application
  5. Resources

1. Introduction

Powered by Reactjs and GraphQl, Gatsby is an open-source static site generator for building high-performance applications. It has numerous plugins that extend its capabilities, for example, the rich ecosystem of data plugins allows it to integrate with headless content management systems, APIs, databases, and many other platforms. It uses GraphQl to query Data and files. A site's interaction and richness depend on images. Gatsby Image offers tools for creating a great experience without affecting performance. By using the Gatsby image plugin, you can add responsive images to a website without affecting performance, and you can even add multiple images at once

Cloudinary is an end-to-end media management platform allowing for image and video storage, dynamic optimization, and responsive delivery. In a gatsby project, the Gatsby-Sourcing-Cloudnary plugin fetches media files from Cloudinary. App-bundle size on the build is reduced as Cloudinary delivers media assets through a content delivery network(CDN). Automatic optimization of quality and format of media files is done by the Gatsby-Source-Cloudinary Plugin

This tutorial steps you into the process of Uploading and fetching Images From Cloudinary in a Gatsby.js Projects

2 Prerequisites

To accomplish this basic knowledge of the following is required

  • ReactJs
  • APIs

3 Getting Cloudinary API keys

To source images from Cloudinary, you must have an account. Cloudinary offers a free tier adequate for starter projects. The following is how to get your Account set up and obtain API keys. i.Log into the Your Cloudinary account (if you don't have one proceed to setup ii. Click on the Dashboard option from the menu. Under Account Details are your Cloud Name, API key, and API Secret.

4 Setting Up a Gatsby Project

You need node.js with its package manager npm to create a Gatsby project. Install the Gatsby CLI globally tool by typing the below command

npm install -g gatsby-cli

Creation Of A new Gatsby Project

Gatsby contains a starter that helps in generating a base setup for your project, Use the command below to generate a Gatsby starter project

npm init gatsby

Follow the prompts to complete the setup. Once done instructions for navigating and running your project will be displayed

cd<Project directory> && run develop

Gatsby simultaneously creates a GraphQl IDE on localhost:8000/___graphql for building GraphQl queries Navigate to localhost:8000 to view your project on a browser. You need to install a few packages for the project -Gatsby plugin image to use while rendering images on a page. In our case, we will use dynamic images and thus use the GatcbyImage component which is used in rendering dynamic images

npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp

Gatsby-source-Cloudinary plugin for fetching images from Cloudinary

npm install gatsby-source-cloudinary

Dotenv to load environment variables from the “.env” file

npm i --save dotenv gatsby-source-cloudinary

Install the transformer plugin use the command:

npm i gatsby-transformer-cloudinary

The plugin uploads image files either by:

  • Uploading images in File nodes
  • Upload remote images by their Url to Cloudinary

Next, we need to configure our gatsby-config.js

i. Import the Dotenv file you installed earlier to the gatsby-confi.js file and add the gatsby-source-Cloudinary plugin with this code. Your code should look something similar to this after importing. Make sure you point your gatsby-source-filesystem to images in your app.

require('dotenv').config();
module.exports = {
  siteMetadata: {
    title: `Cloudinary Images`,
    description: `Get and Upload the images from Cloudinary`,
    author: `Images`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/upload`,
      },
    },
    {
      resolve: 'gatsby-transformer-cloudinary',
      options: {
        cloudName: process.env.CLOUDINARY_CLOUD_NAME,
        apiKey: process.env.CLOUDINARY_API_KEY,
        apiSecret: process.env.CLOUDINARY_API_SECRET,
        uploadFolder: 'Gatsby-images', 
      }
    },
    {
      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`,
      }
    }
  ],
}

Explanation: We import the gatsby-source-filesystem which will allow for files to be uploaded from within Gatsby without having to use an external service like Dropbox or Google Drive. This file system can also be accessed through Cloudinary's API if needed. The gatsby-transformer-cloudinary uses Cloudinary's API to upload images into Gatsby without having to worry about uploading them directly on their servers (which would require authentication). The code shows how to configure the plugin, which is used to upload images from Cloudinary. The code also shows how to use a Gatsby-transformer-Cloudinary plugin. The plugin will take care of uploading images in the src/upload folder and using the cloud name and API key provided by Cloudinary.

ii. At 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

iii. Create a folder with a name of your choice and add some images to it

4. Uploading Image Background

The gatsby-transformer-Cloudinary we installed lets you upload images locally to remote assets to Cloudinary. It also lets you add Gatsby Image support to sourced data from existing Cloudinary assets as well as uploaded ones. Add the following code to your Index.js

  import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
import { useStaticQuery, graphql } from "gatsby"


const IndexPage = () => {
  const data = useStaticQuery(graphql`
        query CloudinaryImages {
            allCloudinaryMedia {
              edges {
                node {
                  secure_url
                }
              }
            }
          }
          `
  );

  const clImages = data.allCloudinaryMedia.edges;

  return (
    <Layout>
    <SEO title="Cloudinary Images" />
      <h2>Remove Image Background using AI</h2>
      <div className="container">
        {clImages.map((image, index) => (
          <div key={`${index}-cl`} className="item">
            <img src={image.node.secure_url} alt="cloudinary-images"/>
          </div>
        ))
      }
      </div>
    </Layout>
  )
}
export default IndexPage

Explanation:

We start by defining an IndexPage function that returns an empty object as its return value. This function takes no arguments and does not have any statements within its body of code Next, we create a variable called clImages which contains all of the Cloudinary Media objects in our database. Then we iterate over each edge in clImages and create divs Once you restart your development server the application will upload your images to a Cloudinary account. It will then fetch and render the images uploaded on your webpage. Congratulations You successfully uploaded and fetched images from Cloudinary!!!

5 Resources

  • GraphQl
  • ReactJs
  • Cloudinary