Access to fetch has been blocked by CORS in NextJS app

Hello!
Whenever my website is loading, each client has to access data from fauna. It works fine on local machine but when deployed to fleek i get the CORS error Access to fetch at 'https://db.eu.fauna.com/' from origin 'https://wild-sound-2562.on.fleek.co' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is the client-side code that accesses the database

  import faunadb from "faunadb";
  const q = faunadb.query;

  const client = new faunadb.Client({
    secret: NEXT_PUBLIC_FAUNA_SECRET,
    domain: "db.eu.fauna.com",
    scheme: "https",
  });

  useEffect(() => {
    /// gets the address of current contract owner
    async function updateUI() {
      const ethers_owner = await administrativeSidechainContract.owner();
      setContractOwner(() => {
        return {
          contractOwner: ethers_owner.toLowerCase(),
        };
      });
      await client
        .query(q.Paginate(q.Match(q.Index("front_data_provider"), "OPEN")))
        .then((ret) => {
          // console.log(ret);
          saved_data = ret;
        })
        .catch((err) =>
          console.error(
            "Error: [%s] %s: %s",
            err.name,
            err.message,
            err.errors()[0].description
          )
        );

      setMatchesData(saved_data);}
updateUI();
  }, []);

and this is my next.config.js file

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  exportTrailingSlash: true, 
};

module.exports = nextConfig;

i tried this approach

const nextConfig = {
  reactStrictMode: true,
  exportTrailingSlash: true, 
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
  },
};

tried like this:

  headers: {
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Allow-Origin": "https://wild-sound-2562.on.fleek.co/",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS",
    "Access-Control-Allow-Headers":
      "Content-Type, Authorization, X-Requested-With",
  },

also tried rewrites approch while adding /api/ at the beginning of the domain when defining client:

const nextConfig = {
  reactStrictMode: true,
  exportTrailingSlash: true, // comment this out when yarn build and yarn next export
  rewrites: [
    {
      source: '/api/:path*',
      destination: 'https://db.eu.fauna.com/:path*',
    },
  ],
};

But nothing seems to work. How do I fix this error?

Hi @sabotage69 and welcome.

We are looking into the CORS issue. Your Fauna client configuration should be good, and there should be no reason to manually provide CORS headers or update your Next config. We will update this post as soon as we can.

Can you share what browser you are using?

Make sure your secret is defined.

I see you specifying NEXT_PUBLIC_FAUNA_SECRET as the secret, but the snippet you shared does not show where that variable is initialized.

If the secret provided is null or undefined then the authorization header will not be sent, which is known to result in a 401 Unauthorized error with a message about CORS.

Side note on configuring the client

Our recent updates to our intelligent routing network means that you should only need to provide the secret and use the driver defaults, which points to https://db.fauna.com. There is no longer a need to specify a different endpoint depending on what Region Group your data is in (For FQL queries)

  const client = new faunadb.Client({
    secret: process.env.NEXT_PUBLIC_FAUNA_SECRET
  });

That said, this is not the source of your problems. Specifying db.eu.fauna.com is also fine, because it points to the same infrastructure.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.