CORS error builder component from @builder.io/react in localhost

I recorded a video, but I couldn’t find a way to send it to you

Hello @Luiz,

Please raise a support ticket with the video attachment and send it to support@builder.io.

Hello @manish-sharma

Sent.

I sent the video, did you watch?

Hello @manish-sharma

I sent the video, did you watch?

Hi @Luiz,

I did watch the video, and currently working on reproducing it.

1 Like

Hello @Luiz,

We have been unable to reproduce this issue on our end. Please review the implementation of the blog article search functionality outlined below:

import React, { useState, useEffect } from 'react';
import { builder, BuilderComponent } from '@builder.io/react';
import { Link } from '@components/Link/Link';
import { Input } from 'theme-ui';

builder.init('API KEY');

const articlesPerPage = 10;

function Blog({ articles }) {
  const [blogItems, setBlogItems] = useState(articles);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      searchBlog(searchTerm);
    }, 500);

    return () => clearTimeout(delayDebounceFn);
  }, [searchTerm]);

  const searchBlog = async (searchText) => {
    const searchResults = await search(searchText);
    setBlogItems(searchResults);
  };

  const search = (searchString) =>
    builder.getAll('blog-article', {
      query: {
        $or: [
          {
            'data.description': {
              $regex: `${searchString}`,
              $options: 'i',
            },
          },
          {
            'data.title': {
              $regex: `${searchString}`,
              $options: 'i',
            },
          },
        ],
      },
    });

  const handleInputChange = (e) => {
    setSearchTerm(e.target.value);
  };

  return (
    <>
      <div style={{ fontSize: '32px', textAlign: 'center' }}>
        <Input defaultValue="" onChange={handleInputChange} />
      </div>

      <BuilderComponent
        key={JSON.stringify(blogItems)} // add key prop
        name="page"
        content={blogItems}
        options={{ includeRefs: true }}
      />
      <div
        style={{
          display: 'flex',
          gap: '2rem',
          marginTop: '20px',
          alignItems: 'center',
          justifyContent: 'center',
          flexWrap: 'wrap',
          maxWidth: '800px',
        }}
      >
        {blogItems.map((item, index) => (
          <div style={{ display: 'flex', color: '#fff', flexWrap: 'wrap' }} key={index}>
            <Link href={`/blog/${item?.data?.handle}`}>
              <div style={{ cursor: 'pointer', overflow: 'hidden', width: 200 }}>
                <div style={{ width: 200, height: 100, display: 'block' }}>
                  <img src={item?.data?.image} alt={item?.data?.title} />{' '}
                  {/* add alt text */}
                </div>
                {item?.data?.title}
              </div>
            </Link>
          </div>
        ))}
      </div>
    </>
  );
}

export async function getStaticProps({ params }) {
  const articles = await builder.getAll('blog-article', {
    // Include references, like the `author` ref
    options: { includeRefs: true },
    limit: articlesPerPage,
  });

  return { props: { articles } };
}

export default Blog;

Does the project need any specific configuration other than apikey? why did I change the component according to your example but it still gives CORS error, this doesn’t make sense

Hello @Luiz,

No there are no other configurations required apart from the API key. Check your next.config.js file, and make sure it includes content security policy header

e.g.

const bundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: !!process.env.BUNDLE_ANALYZE,
})

module.exports = bundleAnalyzer({
  target: 'serverless',
  images: {
    domains: ['res.cloudinary.com', 'cdn.builder.io', 'via.placeholder.com'],
  },
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'Content-Security-Policy',
            value:
              'frame-ancestors https://*.builder.io https://builder.io http://localhost:1234',
          },
        ],
      },
    ]
  },
  env: {
    // expose env to the browser
    BUILDER_PUBLIC_KEY: process.env.BUILDER_PUBLIC_KEY,
    IS_DEMO: process.env.IS_DEMO,
  },
  i18n: {
    // These are all the locales you want to support in
    // your application
    locales: ['en-US'],
    // This is the default locale you want to be used when visiting
    // a non-locale prefixed path e.g. `/hello`
    defaultLocale: 'en-US',
  },
})

Yes, I included content security policy header

Hello @Luiz,

If you’re still experiencing the issue, it might be related to something else, such as the browser or your app implementation. To assist you further, we’ll need a small reproducible case from your code base. A code sandbox would be much appreciated!

Feel free to share the code sandbox or any other relevant details, and we’ll do our best to help you resolve the issue.

hey @manish-sharma

I solved the problem, it was because we are using sentry in our project and in the next.config.js we have this config

module.exports = withSentryConfig(nextConfig, sentryWebpackPluginOptions);

The solution is can be this:

if(process.env.NODE_ENV === ‘development’) {
module.exports = nextConfig;
} else {
module.exports = withSentryConfig(nextConfig, sentryWebpackPluginOptions);
}

or add this line in sentry.client.config.js

tracePropagationTargets: [/^(?!.cdn.builder.io).$/],

Thanks for your time and help.

Hello @Luiz,

We are pleased to hear that. Thanks for sharing the solution!

1 Like