Browser request to https://db.fauna.com/ blocked by CORS policy (401)

My Fauna query from a Next.js app running in Chrome is being blocked by CORS.

My index.js:

import React, { useEffect, useState } from 'react';
import faunadb from 'faunadb';

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

export default function HomePage() {
  const [game, setGame] = useState(null);

  useEffect(() => {
    let stream;

    async function connectAndSubscribeToGame() {
      const test = await client.query(q.Get(q.Match(q.Index('game'))));
    }

    connectAndSubscribeToGame();
  }, []);  // Empty dependency array means this effect runs once on mount

  if (game === null) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Game status: {game.status}</h1>
      <p>Connected users: {game.users.join(', ')}</p>
    </div>
  );
}

and the request being made by my browser:

curl 'https://db.fauna.com/' \
  -H 'authority: db.fauna.com' \
  -H 'accept: */*' \
  -H 'accept-language: en-US,en;q=0.9' \
  -H 'content-type: text/plain;charset=UTF-8' \
  -H 'origin: https://effective-parakeet-6v546g7pwg7fxvv-3000.preview.app.github.dev' \
  -H 'referer: https://effective-parakeet-6v546g7pwg7fxvv-3000.preview.app.github.dev/' \
  -H 'sec-ch-ua: "Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "Chrome OS"' \
  -H 'sec-fetch-dest: empty' \
  -H 'sec-fetch-mode: cors' \
  -H 'sec-fetch-site: cross-site' \
  -H 'user-agent: Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36' \
  -H 'x-faunadb-api-version: 4' \
  --data-raw '{"get":{"match":{"index":"game"},"terms":[]}}' \
  --compressed

response headers:
image

My understanding is that Fauna should be accessible from a browser client. It seems odd that the response does not include any cors related headers.

Thank you in advance for your help!

Hi @john and welcome! :wave:

One thing that stands out to me is that there is no authorization header in your request. Not including an authorization header will result in a CORS error. The 401 Unauthorized error also makes sense in this context.

Are you sure that process.env.FAUNA_API_KEY variable is defined? Since this is a client-side query, you may need to perfix the environment variable with NEXT_PUBLIC_. See Next.js documentation on exposing env vars to the browser.

:person_facepalming: yep that’s what it was. Thank you for your help and prompt response, I really appreciate it.

1 Like

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