Last active
October 12, 2023 08:24
-
-
Save codeflorist/1f69841552e3a610219516542a82ab7b to your computer and use it in GitHub Desktop.
Custom nuxt/image provider for the Storyblok Image Service v1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Provider to use the old storyblok image service v1 | |
with the nuxt/image package. | |
Why use v1 instead of the new v2? | |
Because v2 has serious problems with CDN caching, | |
with cloudfront CDN cache invalidating every day | |
instead of 1 year. This leads to response times | |
of up to multiple seconds due to re-generation | |
of the image service. Sadly, Storyblok has not yet | |
even acknowledged this problem, let alone fixed it. | |
v1 keeps the CDN cache for 1 year as it should. | |
Usage (see https://image.nuxt.com/advanced/custom-provider): | |
- Copy this file to `~/image-providers/storyblok-v1-image-provider.ts` | |
- Adapt the nuxt/image config in your nuxt.config.ts: | |
image: { | |
providers: { | |
customProvider: { | |
name: 'storyblok-v1', | |
provider: '~/image-providers/storyblok-v1-image-provider.ts', | |
}, | |
}, | |
provider: 'storyblok-v1', | |
}, | |
*/ | |
import { withBase, joinURL, parseURL } from 'ufo' | |
const storyblockCDN = 'https://img2.storyblok.com' | |
export const getImage = (src, { modifiers = {}, baseURL = storyblockCDN } = {}) => { | |
const { fit, smart, width = '0', height = '0', filters = {}, format, quality } = modifiers | |
const isSVG = src.endsWith('.svg') | |
const doResize = !isSVG && (width !== '0' || height !== '0') | |
if (!isSVG) { | |
if (format) { | |
filters.format = format + '' | |
} | |
if (quality) { | |
filters.quality = quality + '' | |
} | |
} | |
const _filters = Object.entries(filters || {}) | |
.map((e) => `${e[0]}(${e[1]})`) | |
.join(':') | |
const options = joinURL( | |
fit ? `fit-${fit}` : '', | |
doResize ? `${width}x${height}` : '', | |
smart ? 'smart' : '', | |
_filters ? 'filters:' + _filters : '' | |
) | |
const { pathname } = parseURL(src) | |
const url = withBase(joinURL(options, pathname), baseURL) | |
return { | |
url, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment