I have two apps – CRA running on port 3000, and Next running on 3005.
In Next app I have simple message event listener:
useEffect(() => {
const handleMessage = (event: MessageEvent<{}>) =>
console.log('Message event: ', event);
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
And I’ve set up headers in next.config.js
:
const securityHeaders = [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: '*' },
{
key: 'Access-Control-Allow-Methods',
value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
},
{
key: 'Access-Control-Allow-Headers',
value:
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
},
];
const nextConfig = {
async headers() {
return [
{
// Apply these headers to all routes in your application.
source: '/:path*',
headers: securityHeaders,
},
];
},
};
module.exports = nextConfig;
In React app I’m calling postMessage
through iframe tag like this:
export const Frame = () => {
const frameRef = useRef<HTMLIFrameElement>(null);
const handleFrameLoad = () => {
frameRef?.current?.contentWindow?.postMessage('TEST');
};
return (
<iframe
src="http://localhost:3005"
ref={frameRef}
onLoad={handleFrameLoad}
sandbox="allow-same-origin allow-scripts"
/>
);
};
And I’m still receiving error below in CRA’s console.
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:3005').
Is there anything else that I can do to allow postMessage communication between two different local ports in NextJS?