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

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:

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.
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.
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():

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

This should resolve most of your errors.

You may still see this one:

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.

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

Keep on BUIDLing,

MG


More Posts

Cover Image for One Key Trick for Building Bulletproof Components That Work in Pages Editor

One Key Trick for Building Bulletproof Components That Work in Pages Editor

> Developers face the same key challenge when building for Pages as they did for the Experience Editor

Cover Image for SitecoreAI Search Experiences: A First Look

SitecoreAI Search Experiences: A First Look

> And how it is different from Sitecore Search