Last active
October 31, 2024 13: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 hidden or 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 v2? | |
- v1 has the filters in the middle of the URL, | |
leaving the filename at the end, which has | |
benefits for SEO and when downloading the images. | |
- v1 has better CDN caching. v2 has problems | |
with the Cloudfront CDN cache invalidating every day | |
instead of 1 year. | |
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', | |
options: { | |
baseURL: 'https://img2.storyblok.com' | |
} | |
}, | |
}, | |
provider: 'storyblok-v1', | |
}, | |
*/ | |
import type { ProviderGetImage } from '@nuxt/image' | |
import { withBase, joinURL, parseURL } from 'ufo' | |
export const getImage: ProviderGetImage = ( | |
src, | |
{ modifiers = {}, baseURL } = {} | |
) => { | |
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