NextJS: Access has been blocked by CORS policy

> CORS is almost as much of a nuisance as GDPR popups
Cover Image for NextJS: Access has been blocked by CORS policy
Marcel Gruber

You finally managed to get your Next.js-based JSS application loading in the Experience Editor, but then you start noticing intermittent errors and a crowded browser console error log. Let's address some of those issues.

Errors

Here are some of the errors you might see:


_1
Access to resource at 'http://localhost:3000/_next/webpack-hmr' from origin 'https://sitecore102u0.sc' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


_1
sitecore102u0.sc/:1 Access to fetch at 'http://localhost:3000/_next/static/development/_devMiddlewareManifest.json' from origin 'https://sitecore102u0.sc' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


_1
page-loader.js?e87a:46 GET http://localhost:3000/_next/static/development/_devMiddlewareManifest.json net::ERR_FAILED 200

The Fix

Add this to your next.config.js file above or below async rewrites():


_11
async headers() {
_11
return [
_11
{
_11
source: '/_next/:path*',
_11
headers: [
_11
{ key: 'Access-Control-Allow-Origin', value: process.env.SITECORE_API_HOST || 'https://sitecore102u0.sc' },
_11
{ key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS' },
_11
],
_11
},
_11
];
_11
},

This should resolve most of your errors.

You may still see this one:


_1
Warning: Prop `phkey` did not match.

According to Sitecore, it doesn't affect content editing and it can be ignored. Sitecore says this error affects XP 10.1, but I am also seeing it in 10.2.

I'm also seeing this one, but no fix yet... I reached out to Sitecore support and they said that the related bug 463325 is still open as of 23 Nov, 2022.


_1
GET http://localhost:3000/_next/webpack-hmr 404 (Not Found)

Keep on BUIDLing,

MG


More Stories