New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

gatsby-transformer-cloudinary

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

gatsby-transformer-cloudinary

Transform local files into Cloudinary-managed assets for Gatsby sites.

  • 1.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
264
decreased by-30.71%
Maintainers
1
Weekly downloads
 
Created
Source

gatsby-transformer-cloudinary

Creates CloudinaryAsset nodes from compatible File nodes. The File nodes are uploaded to Cloudinary, and the CloudinaryAsset responses are made up of Cloudinary URLs to transformed images in a format that‘s compatible with gatsby-image.

You’ll need a Cloudinary account to use this plugin. They have a generous free tier, so for most of us this will stay free for quite a while.

Live demo (source)

DISCLAIMER: If you try running this demo's source code on your own computer, you might face issues as the demo uses assets and transformations from the author’s Cloudinary account. Before running, please remove them or replace them with images and transformations from your own Cloudinary account.

Features

  • Upload local project media assets to a secure remote CDN
  • Upload remote media assets to a secure remote CDN
  • Utilize media assets on Cloudinary in gatsby-image
  • Use gatsby-image fluid and fixed formats on Cloudinary assets
  • Retrieve media files in optimized formats with responsive breakpoints
  • Utilize all Cloudinary transformations including chained transformations in gatsby's data layer

Example usage

Here's the plugin in action to fetch a fixed asset using the useStaticQuery API of gatsby:

import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Image from 'gatsby-image';

export default () => {
  const data = useStaticQuery(graphql`
    query {
      file(name: { eq: "marketplace-banner" }) {
        childCloudinaryAsset {
          fixed {
            ...CloudinaryAssetFixed
          }
        }
      }
    }
  `);

  return (
    <div>
      <h2>Here goes something</h2>
      <Image fixed={data.file.childCloudinaryAsset.fixed} alt="banner" />
    </div>
  );
};

Installation

This transformer automatically creates childCloudinaryAsset nodes for File nodes created by gatsby-source-filesystem.

This transformer also allows you to pass URLs directly to Cloudinary to side-step the need to first download files to your development machine. This can be achieved by calling the createRemoteImageNode function from an onCreateNode function.

Install the plugins using either npm or yarn.

npm install --save gatsby-transformer-cloudinary gatsby-source-filesystem
yarn add gatsby-transformer-cloudinary gatsby-source-filesystem

How to use

Set up environment variables

Add the data that shouldn’t be committed to Git into .env.development:

# Find these values at https://cloudinary.com/console/
CLOUDINARY_CLOUD_NAME=<your cloud name>
CLOUDINARY_API_KEY=<your API key>
CLOUDINARY_API_SECRET=<your API secret>

NOTE: you’ll also need to set these environment variables in your build system (i.e. Netlify).

Configure the plugin

In your gatsby-config.js, point gatsby-source-filesystem to images in your app, then set up gatsby-transformer-cloudinary with your credentials.

// Load the environment variables.
require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
});

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    {
      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-cloudinary',
      },
    },
  ],
};

To directly upload images to Cloudinary from remote sources, you can use the createRemoteImageNode function:

// gatsby-node.js
import { createRemoteImageNode } from 'gatsby-transformer-cloudinary';

// This example assumes "post" nodes are created in a `sourceNodes` function.
const POST_NODE_TYPE = 'post';

export async function onCreateNode({
  node,
  actions: { createNode },
  createNodeId,
  createContentDigest,
  reporter,
}) {
  // In this example, "post" nodes sometimes have a "cover_photo_url" that's a link to an image.
  if (node.internal.type === POST_NODE_TYPE && node.cover_photo_url) {
    await createRemoteImageNode({
      url: node.cover_photo_url,
      parentNode: node,
      relationshipName: 'coverPhoto',
      createNode,
      createNodeId,
      createContentDigest,
      reporter,
    });
  }
}

Plugin options

In gatsby-config.js the plugin accepts the following options:

optiontyperequireddefault valuedescription
cloudNameStringtruen/aCloud name of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
apiKeyStringtruen/aAPI Key of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
apiSecretStringtruen/aAPI Secret of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
uploadFolderStringfalsen/aAn optional folder name where the uploaded assets will be stored on Cloudinary.
fluidMaxWidthIntfalse1000The maximum width needed for an image. If specifying a width bigger than the original image, the width of the original image is used instead. Used when calculating breakpoints.
fluidMinWidthIntfalse50The minimum width needed for an image. Used when calculating breakpoints.
createDerivedBooleanfalsefalseIf true, create and keep the derived images of the selected breakpoints during the API call. If false, images generated during the analysis process are thrown away. This option is ignored if useCloudinaryBreakpoints is false. It's recommended that you enable createDerived if useCloudinaryBreakpoints is true to store the breakpoint images and prevent them from being recalculated on every build.
breakpointsMaxImagesIntegerfalse20Set maximum number of responsive breakpoint images generated and returned on image upload. If useCloudinaryBreakpoints is false, then exactly breakpointsMaxImages breakpoints will be created.
useCloudinaryBreakpointsBooleanfalsefalseIf true, then Cloudinary will be requested to automatically find the best breakpoints for each image. It's recommended that this option be set to false in development because this option uses one Cloudinary transformation for every image uploaded to Cloudinary plus one transformation for every derived image created while calculating breakpoints.
overwriteExistingBooleanfalsefalseWhether to overwrite existing assets with the same public ID. When set to false, return immediately if an asset with the same Public ID was found. It's recommended that this is set to false in development as each image overwrite costs one Cloudinary transformation.

Note: Each derived image created for a breakpoint will consume one Cloudinary transformation. Enable the useCloudinaryBreakpoints option with care. If the createDerived option is enabled, transformations will only be consumed when the images are first created. However, created images will consume Cloudinary storage space. If overwriteExisting is enabled, each image that you upload will consume one transformation each time your Gatsby cache gets cleared and the image gets re-uploaded. For this reason, it's recommended that you keep overWriteExisting disabled and instead set the overwriteExisting parameter of createRemoteImageNode on a per-image basis when you know that an image has actually been updated.

Query for images

Assuming you have an image called “avatar.jpg” in your src/images/ directory, you can use it in a component like this:

import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Image from 'gatsby-image';

export default () => {
  const data = useStaticQuery(graphql`
    query {
      file(name: { eq: "avatar" }) {
        childCloudinaryAsset {
          fluid {
            ...CloudinaryAssetFluid
          }
        }
      }
    }
  `);

  return <Image fluid={data.file.childCloudinaryAsset.fluid} alt="avatar" />;
};

Avoiding stretched images using the fluid type

As mentioned previously, images using the fluid type are stretched to match the container’s width and height. In the case where the image’s width or height is smaller than the available viewport, the image will stretch to match the container, potentially leading to unwanted problems and worsened image quality.

The CloudinaryAssetFluidLimitPresentationSize fragment can be used to to gatsby-image not to stretch an image larger than its maximum dimensions regardless of the size of its container:

query {
  file(name: { eq: "avatar" }) {
    childCloudinaryAsset {
      fluid {
        ...CloudinaryAssetFluid
        ...CloudinaryAssetFluidLimitPresentationSize
      }
    }
  }
}

Manual Usage

It’s also possible to manually create gatsby-image-friendly fixed and fluid objects by importing helper functions from the transformer.

This is an advanced use case — if possible, try not to do this when Gatsby’s data layer is an option. This is intended for cases where assets are already on Cloudinary and moving them to the Gatsby project would be too time-intensive to be reasonable.

NOTE: This approach is async, which means you’ll end up with content jumping unless you manually account for the image area. You’ve been warned.

Manually creating fluid images

import React from 'react';
import Image from 'gatsby-image';
import { getFluidImageObject } from 'gatsby-transformer-cloudinary';

export default () => {
  const [fluid, setFluid] = useState(false);

  useEffect(() => {
    getFluidImageObject({
      public_id: 'gatsby-cloudinary/jason',
      cloudName: 'jlengstorf',
      originalHeight: 3024,
      originalWidth: 4032,
      breakpoints: [200, 400, 600, 800],
      transformations: ['ar_16:10', 'c_fill'],
      chained: ['e_grayscale,e_tint:100:663399:0p:white:100p', 't_lwj'],
    }).then(result => setFluid(result));
  }, []);

  return fluid ? <Image fluid={fluid} alt="Jason" /> : <p>loading...</p>;
};

Manually creating fixed images

import React from 'react';
import Image from 'gatsby-image';
import { getFixedImageObject } from 'gatsby-transformer-cloudinary';

export default () => {
  const [fixed, setFixed] = useState(false);

  useEffect(() => {
    getFixedImageObject({
      public_id: 'gatsby-cloudinary/jason',
      cloudName: 'jlengstorf',
      originalHeight: 3024,
      originalWidth: 4032,
    }).then(result => setFixed(result));
  }, []);

  return fixed ? <Image fixed={fixed} alt="Jason" /> : <p>loading...</p>;
};

API

This plugin can support both the fixed and fluid formats for gatsby-image.

Both fixed and fluid accept arguments. All arguments are optional.

Arguments for both fixed and fluid

argumenttyperequireddefaultdescription
cloudNameStringtruen/aCloud name of your Cloudinary account, can be obtained from your Cloudinary console. This should be stored and retrieved as an environment variable.
public_idStringtruen/aPublic ID of the image to retrieve from Cloudinary. This can be obtained from your Cloudinary account.
transformations[String!]false[]Array of transformations to be applied to the image.
chained[String!]false[]An array of chained transformations to be applied to the image.
defaults[String!]false["f_auto", "q_auto"]Default transformation applied to the image
originalHeightInttruen/aHeight of the image fetched. This is required in gatsby-image to calculate the aspect ratio of the image.
originalWidthInttruen/aDesired width of the image. This is required in gatsby-image to calculate the aspect ratio.
base64WidthStringfalse30Base64 width of the image.
versionBooleanfalsefalseVersion number of image if applicable, eg. 300124291, 1241983.

Arguments for fixed

argumenttypedefaultdescription
widthInt400The width that the image should display at.

Arguments for fluid

argumenttypedefaultdescription
maxWidthIntOriginal width of the imageThe maximum width for fluid images.

A note about aspect ratios

You’re able to change the aspect ratio of images by supplying the aspect ratio parameter in the transformations argument.

NOTE: The aspect ratio must be supplied in the transformations array. It will not be picked up from the chained argument.

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

Keywords

FAQs

Package last updated on 24 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc