Using Cloudinary as a write-through cache for a Netlify Function that generates images

Share this video with your friends

Send Tweet

Every time we hit our function it runs the headless browser and regenerates the image. We can fix this by using Cloudinary as a write-through cache in front of our Netlify opengraph image generation function. If the image exists, Cloudinary will return it, if not it will ask our function to generate it, then cache it.

Joel Hooks
Joel Hooks
~ 5 years ago

I had some challenges with this episode around the Cloudinary URL signing. It consistently generated URLs with a rogue / whenever I used the ? to add the query params.

const qs = require('querystring')

exports.handler = async function (event, ctx) {
  const {queryStringParameters} = event
  try {
    const imageUrl = `https://res.cloudinary.com/${
      process.env.CLOUD_NAME
    }/image/fetch/${encodeURIComponent(
      `https://competent-goodall-d71d0d.netlify.com/.netlify/functions/gen-opengraph-image?${qs.stringify(
        queryStringParameters,
      )}`,
    )}`
    return {
      statusCode: 302,
      headers: {
        Location: imageUrl,
      },
      body: '',
    }
  } catch (e) {
    console.log(e)
  }
}

I ended up using this for my process-url function. It utilizes Cloudinary's fetch functionality to forward a URL and has the same basic end result as it utilizes the can and caching!

Invalidating the cache isn't something that I explored.

I created a post on the Cloudinary community support forum describing the issue I ran in to and also had a debugging session with Chris on Twitter.

Lauro Silva
Lauro Silva
~ 5 years ago

I ran into the same issue. I decided to go with Joel's implementation. Note: the fetch method is disabled by default for any new account.

To enable it, you need to navigate to the following page:

https://cloudinary.com/console/c-4aee1e8012de758933b9f51d526756/settings/security

and uncheck the box next to Fetched URL in the "Restricted media types" section.

Joel Hooks
Joel Hooks
~ 5 years ago

The Cloudinary team also posted a workaround for making the signed URL approach work and mentioned that they would be patching a proper fix in future versions.

~ 2 years ago

Im struggling with this part, when i run cloudinary.url I'm getting the 1x1 transparent pixel url back, not the URL that has the fn_pre:remote stuff in it, any one else having this problem?

Lucas Minter
Lucas Minter
~ 2 years ago

Hey! Here are more examples of getting OG images working that use this pattern: https://github.com/eggheadio/eggheadio-course-notes/tree/main/building-an-opengraph-image-generation-api-with-cloudinary-netlify-functions-and-react-914e