Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
React and Next postMessage communication CORS problem

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda