Server key doesn't work from a browser script?

I’ve used a server key successfully from the CLI. I wrote a little JavaScript to run from a browser using the server key (not intended for production) but I get Unauthorized. Am I right to guess that Fauna will not accept the server key when code is running from a browser? How do I access Fauna directly from the browser (not using Node or any framework)? I saw in the docs that a “client key” is deprecated. Is there an example of accessing Fauna in vanilla JS directly from the browser? Here’s the code I tried:

 import faunadb from 'https://jspm.dev/npm:faunadb@2.14.2'
const FAUNA_SERVER_KEY = "mysecret-works-in-CLI-but-not-browser";
const q = faunadb.query;
const client = new faunadb.Client({
  secret: 'FAUNA_SERVER_KEY'
});
client.query(
  q.CreateCollection({ name: 'spells' })
)
.then((ret) => console.log(ret))

Hey Daniel,

this is very similar to another question I recently answered: User authentication with Graph QL? which answers how to access FaunaDB if ‘client keys’ are deprecated and explains you how to create the correct roles.

Although that question is in a GraphQL context, the logic is exactly the same since the roles and auth are always in FQL :slight_smile:. So I think you will find all the information you need there.

No, to my konwledge, that’s not the case, a correct key or token is correct and remains correct in whatever context it is used so something else must be going on. When you say CLI, what CLI is that? The fauna shell, the fauna UI dashboard or simply the same code ran via a node script?

A server key should definitely have access to create a collection in each case.

I just thought of something.
Do you happen to have written a security Role somewhere that uses Identity()?
If so, that role will crash since a server key does not have an identity. If not, please contact me and send instructions on how to reproduce this so I can help you further.

$ fauna shell --secret=mysecret-works-in-CLI-but-not-browser
Connected to https://db.fauna.com
Type Ctrl+D or .exit to exit the shell
> CreateCollection({ name: "users" })
{
  ref: Collection("users"),
  ts: 1597749033055000,
  history_days: 30,
  name: 'users'
}
>

The Fauna shell works with the server key.

I’ve haven’t written any roles, just created “new key” “server”.

Hey Daniel,

I tried it out and then noticed something. You are passing in the string ‘FAUNA_SERVER_KEY’ instead of the variable FAUNA_SERVER_KEY. I assume that might be your problem?

Oh wow. I missed that! Thank you. All along I imagined it was something difficult!

Just wanted to say thank you for the fast response and the thoughtful (and kind) approach. It’s a very welcoming introduction to the Fauna community!

1 Like

You’re welcome :slight_smile:.