Git Product home page Git Product logo

gatsby-source-cloudinary's Introduction

Gatsby-Source-Cloudinary

This source plugin queries media files from a Cloudinary account into cloudinaryMedia nodes in your Gatsby project.

See a live demo here

Here's a tutorial on plugin usage

Motivation

Gatsby offers the ability to develop high performance web pages with a rich developer experience and declarative data fetching Layer with GraphQL. Cloudinary provides a robust solution to manage media assets, from storage, optimized delivery, to media transformations. Extending the powers of Gatsby with the use of gatsby-source-cloudinary affords the best of both worlds, to allow users store media assets on Cloudinary, leveraging Cloudinary's powerful optimization and transformation capabilities in fast sites built with Gatsby.

While Cloudinary images with on-the-fly transformations can be used during runtime in Gatsby, gatsby-source-cloudinary utilizes the build optimizations of Gatsby.

Features

  • Store media files on Cloudinary and deliver through a secure CDN to your Gatsby site
  • Average of over 60% image optimizations using f_auto and q_auto applied by default.
  • Query Cloudinary images in Gatsby's data layer using GraphQL.
  • Utilize Cloudinary's robust transformation suite in media files on a Gatsby site.
  • Manage media assets of an application completely on Cloudinary rather than directly in the codebase.

Looking to use the features of Gatsby-Image with Cloudinary optimized storage, transformations and delivery? Checkout the gatsby-transformer-cloudinary plugin.

Example usage

Here's a sample usage of the source plugin to create an image gallery from images stored on Cloudinary:

import React from 'react'
import {useStaticQuery, graphql} from 'gatsby'

const SingleImage = () => {
    const data = useStaticQuery(graphql`
        query CloudinaryImage {
            cloudinaryMedia(public_id: {eq: "gatsby-source-cloudinary/11"}) {
                secure_url
              }
          }
          `
    );
    const clImage = data.cloudinaryMedia.secure_url;

    return (
        <div>
          <div>
             <img src={clImage} alt={"no alt :("} />
          </div>
        </div>
      )
  }

Installation

Install the source plugin using either npm or yarm:

npm install --save gatsby-source-cloudinary

Cloudinary Credentials

Cloudinary offers a generous free tier which is more than enough to bootstrap projects. Obtain your cloudname, key and secret from your cloudinary console when you signup at Cloudinary.com.

Environment configuration

Store your cloudName, apiKey and apiSecret as environment variables for security. To do this, create a file in the root of the project named .env. Add your environment variables in it with:

CLOUDINARY_API_KEY=INSERT API KEY HERE
CLOUDINARY_API_SECRET=INSERT API SECRET HERE
CLOUDINARY_CLOUD_NAME=INSERT CLOUDNAME HERE

Install dotenv in your project with:

yarn add dotenv

In your gatsby-config.js file, require and configure dotenv with:

require('dotenv').config();

There are several options to configuring dotenv to use different env files either in development or production. You can find that here.

Add the .env file to .gitignore so it's not committed.

Ensure to configure the environment variables on deployment as well.

Plugin setup

In your gatsby-config.js file, include the plugin like this:

{
    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`,
      type: `type Value`,
      prefix: `abc-xyz/`,
      transformations: {
        auto: { quality: 'auto', fetch_format: 'auto' }
      }
    }
}

Plugin options

You can find the plugin options in the table below.

option type required default description
cloudName string true n/a Cloud name of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
apiKey string true na/a API Key of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
apiSecret string true n/a API Secret of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
resourceType string false image This is the type of file. Possible values: image, raw, video. Note: Use the video resource type for all video resources as well as for audio files, such as .mp3.
type string false all This is the storage type: upload, private, authenticated, facebook, twitter, gplus, instagram_name, gravatar, youtube, hulu, vimeo, animoto, worldstarhiphop or dailymotion.
maxResults integer false 10 Max number of resources to return
tags boolean false false If true, include the list of tag names assigned to each resource
prefix string false n/a Find all resources with a public ID that starts with the given prefix. The resources are sorted by public ID in the response.
context boolean false n/a Specifies if the context data for the image should be returned. This is useful for retrieving alt text or custom metadata in key:value pairs for an image set on Cloudinary.
transformations object false {} Adds Cloudinary transformation options.

With prefix, you can source only media files from a specific folder. However, you will need to specify type and resourceType in the config options.

An example prefix value is gatsby-anime-videos/. This will fetch only media files with public ids beginning with gatsby-anime-videos/*. Example: gatsby-anime-videos/naruto.mp4

All media files sourced from Cloudinary are done when Gatsby creates an optimized build, hence you will need to trigger a new production build whenever new media files are added directly on Cloudinary.

How to use

Once a development server is started using gatsby develop, all media assets configured in the plugin are available as cloudinaryMedia and allCloudinaryMedia in GraphQL. These can run in a Page Query or StaticQuery.

import React from 'react'
import {useStaticQuery, graphql} from 'gatsby'


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

    return (
        <div>
          <div>
            {clImages.map((image, index) => (
                  <div key={`${index}-cl`}>
                    <img src={image.node.secure_url} />
                  </div>
                ))
            }
          </div>
        </div>
      )
  };

Transformations

Cloudinary supports image transformations to be defined either "on the fly" (by adding transformation options to the asset's URL) or as named transformations which are prerendered during the upload phase. You can add both kinds of transformations using the transformations option. The URLs containing all transformation parameters are then added to the GraphQL schema. See Cloudinary's full list of image transformation options here.

Here's an example of how to use transformations in this plugin:

gatsby-config.js:

{
  resolve: 'gatsby-source-cloudinary',
  options: {
    //...
    transformations: {
      // automatic quality & format choice (webp in Chrome)
      auto: { quality: 'auto', fetch_format: 'auto' }, 
      // named transformation, must be defined in Cloudinary upfront
      maxeco: 'maxeco', 
      // maximum condensed thumbnail
      thumb: { quality: 20, width: 200, format: 'webp' },
      // cropping to faces with AI
      cropped: { width: 400, height: 400, gravity: 'faces', crop: 'fill' }
    },
  },
},

and in your GQL queries:

query TransformedCloudinaryMedia {
  allCloudinaryMedia {
    edges {
      node {
        # the original asset
        secure_url
        auto {
          # -> /image/upload/f_auto,q_auto/v1/<asset>.jpg
          url
          secure_url
        }
        maxeco {
          # -> /image/upload/t_maxeco/v1/<asset>.jpg
          url
          secure_url
        }
        thumb {
          # -> /image/upload/q_20,w_200/v1/<asset>.jpg
          url
          secure_url
        }
        cropped {
          # -> /image/upload/c_fill,g_faces,h_400,w_400/v1/<asset>.jpg
          url  
          secure_url
        }
      }
    }
  }
}

Other Resources

Contribute

Want to contribute to make this tool even better? Feel free to send in issues and pull requests on feature requests, fixes, bugs, typos, performance lapses or any other challenge faced with using this tool.

License

MIT

gatsby-source-cloudinary's People

Contributors

chuloo avatar nirmaoz avatar elmariachi111 avatar cbaucom avatar kosai106 avatar deathborn avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.