In my nextjs project, I'm using <Image />
component from next/image. I'm accessing images from a CDN hosted in digitalOcean server. For some reason CORS policy for the CDN isn't working properly, so images don't load in my browser (using Chrome). When I use default loader of nextjs, images works fine, coz I have seen that next/image works like request is sending from the same origin (https://localhost:3000/_next/image?url=imageUrl), so cors error doesn't occur. But default loader doesn't work with next export
. So I had to use akamai loader instead of default loader. For using akamai loader, now images are being called directly using imgUrl (https://example.com/slider.jpg). I have tried multiple solutions but can't solve the problem.
CORS error -
Access to image at 'https://someCDNurl/promotion/ac-1.JPG' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
At last, I have tried to add custom response header Access-Control-Allow-Origin: *
. But this header works for fetching resources from the pages I guess. But I don't know how to set headers for specific url like https://example.com/
that gets fetched by the browser.
Can anyone tell me how to add a custom header for fetching resource from specific url or any other way/hack to solve this problem?
I'm using nextjs version 11. My next.config.js
:
/* const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
}) */
module.exports = ({
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Access-Control-Allow-Origin',
value:
'*',
},
],
},
]
},
devIndicators: {
autoPrerender: false,
},
images: {
domains: ['example1.com', 'example2.com'],
loader: 'akamai',
path: '',
disableStaticImages: false,
minimumCacheTTL: 60,
formats: ['image/webp'],
},
reactStrictMode: true,
env: {
PG_PUBLIC_KEY: process.env.PG_PUBLIC_KEY,
PRIVATE_KEY : process.env.PRIVATE_KEY,
MERCHANT_ID : process.env.MERCHANT_ID,
NAGAD_BASE_URL : process.env.NAGAD_BASE_URL,
MERCHANT_NUMBER : process.env.MERCHANT_NUMBER,
MERCHANT_CALLBACK_URL: process.env.MERCHANT_CALLBACK_URL,
},
});
My image component in the frontend:
import Image from 'next/image';
<Image
unoptimized={true}
//loader={myLoader}
// src={item.imgUrl}
crossOrigin="anonymous"
src={getImgUrl(item.imgUrl)}
height={200}
width={410}
layout="responsive"
objectFit="cover"
alt="banner"
/>