Skip to content

Commit

Permalink
Fix cms-kontent example Next/Image domain error (#37188)
Browse files Browse the repository at this point in the history
* Fixes the following error in the `cms-kontent` example by implementing
  an `Image` component to wrap `Next/Image` with a custom loader.

```
Invalid src prop ... hostname "assets-eu-01.kc-usercontent.com" is not configured under images in your `next.config.js`
```

* This error is affecting both the `pages/index.js` and
  `pages/posts/[slug].js` routes.
* Uses a custom loader rather than adding the Kontent asset domains to
  `next.config.js` as we can transform the images using the Kontent
  Delivery API directly rather than delegating this to the Next app web
  server.

Ref:
* https://nextjs.org/docs/messages/next-image-unconfigured-host
* https://nextjs.org/docs/basic-features/image-optimization
* https://meeg.dev/blog/using-the-next-image-component-with-kentico-kontent-assets
* https://github.com/Kentico/kontent-starter-corporate-next-js/blob/b7c9ef588c2e316557095e3160e712a1220601f5/components/Image.js
* https://kontent.ai/learn/reference/image-transformation/
  • Loading branch information
tommarshall committed May 25, 2022
1 parent d9b6d99 commit 82a9d21
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion examples/cms-kontent/components/avatar.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Image from 'next/image'
import Image from '../components/image'

export default function Avatar({ name, picture }) {
return (
Expand Down
2 changes: 1 addition & 1 deletion examples/cms-kontent/components/cover-image.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import cn from 'classnames'
import Image from 'next/image'
import Image from '../components/image'
import Link from 'next/link'

export default function CoverImage({ title, src, slug }) {
Expand Down
32 changes: 32 additions & 0 deletions examples/cms-kontent/components/image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import NextImage from 'next/image'
import { transformImageUrl } from '@kentico/kontent-delivery'

const KONTENT_ASSET_HOSTNAME_REGEX = /.kc-usercontent.com$/

const getLoader = (src) => {
return srcIsKontentAsset(src) ? kontentImageLoader : undefined
}

const srcIsKontentAsset = (src) => {
try {
const { hostname } = new URL(src)
return KONTENT_ASSET_HOSTNAME_REGEX.test(hostname)
} catch {
return false
}
}

const kontentImageLoader = ({ src, width, quality = 100 }) => {
return new transformImageUrl(src)
.withWidth(width)
.withQuality(quality)
.withCompression('lossless')
.withAutomaticFormat()
.getUrl()
}

export default function Image(props) {
const loader = getLoader(props.src)

return <NextImage {...props} loader={loader} />
}

0 comments on commit 82a9d21

Please sign in to comment.