Next.js Discord

Discord Forum

How can I easily set "unoptimized" prop for every image from my CDN?

Answered
Southeastern blueberry bee posted this in #help-forum
Open in Discord
Avatar
Southeastern blueberry beeOP
I am slowly putting images from one server to my CDN. CDN images are already .webp and optimized, so I would like to globally disable optimization but only for images from CDN. I tried custom loader with mimicing Next link but it didn't work. I just got 404 when I made it:

http://localhost:3000/_next/image?url=https%3A%2F%2Flink.com%2Fyyy.jpeg?w=256&q=75

This link without "customLoader" works perfectly. Assuming that my CDN link is:
cdn.abc.com how can I force "unoptimized" to every <Image> component that has that link? Only idea I have is creating something like this:
Image
Answered by Pearls
The nextjs image component automatically optimizes all images, you could possibly write a custom component that would render a normal img tag when the image comes from your cdn and render nextjs’s image component when it doesnt come from your cdn, heres an example:

import Image from 'next/image';

const CustomImage = ({ src, alt, ...props }) => {
const isExternal = src.startsWith('https://cdn.example.com/');

if (isExternal) {
return <img src={src} alt={alt} {...props} />;
} else {
return <Image src={src} alt={alt} {...props} />;
}
};

export default CustomImage;
View full answer

5 Replies

Avatar
Rainbow trout
Inside your next config:
module.exports = {
  images: {
    unoptimized: true,
  },
}
Might be able to do something with it there, not sure tho
Avatar
The nextjs image component automatically optimizes all images, you could possibly write a custom component that would render a normal img tag when the image comes from your cdn and render nextjs’s image component when it doesnt come from your cdn, heres an example:

import Image from 'next/image';

const CustomImage = ({ src, alt, ...props }) => {
const isExternal = src.startsWith('https://cdn.example.com/');

if (isExternal) {
return <img src={src} alt={alt} {...props} />;
} else {
return <Image src={src} alt={alt} {...props} />;
}
};

export default CustomImage;
Answer
Avatar
Southeastern blueberry beeOP
Thanks. I was thinking of custom <Image> component - that's closest to what I want to achieve. Thank you.
Avatar
👍 You’re welcome :D