Getting started with Fauna and Node.js using Fastify

Today we’ll be building a small API to see a quick overview on how to use Fauna in Node.js.

For reference, here’s a Github repository with the finished project that you can use to follow along:

Any recent version of Node will do. If you don’t have it installed already, I recommend downloading the LTS installer from the official website. This will also install NPM which you need to manage your dependencies.

For our server we’ll be using Fastify which is easy to use and offers a great developer experience. Also, as its name implies, it’s very fast.

One last thing. If you’ve never used Fauna or FQL before, it would be a good idea to at least take a quick look at this introductory article.

In this article:

  • First steps
  • Initializing Fauna
  • Preparing our data
  • Installing Nodemon and Dotenv
  • Creating a custom error class
  • Creating users
  • Authenticating users
  • Retrieving a user
  • Deleting a user
  • Setting up fine-grained permissions

First steps

To get started, create a folder for your project and access it from your terminal. Then initialize NPM with this command:

This should create a package.json file in your project folder which we can ignore for now.

Next, we’re going to install our first dependencies:

Finally, create an index.js in your project folder file with this:

Let’s test everything is working as expected with this command:

You should see something similar to this:

You can stop the server at any time with Control + C in your terminal.

Initializing Fauna

After you’ve created a free Fauna account and logged into the dashboard, you’re ready to create a new database.

I will be using NODEJS_TUTORIAL but you can use any name you prefer:

Creating a server key

To be able to access our database from our code we need to create a server access key.

Go to the security section of the dashboard and create a new key. In the settings give it a role of Server:

After creating this key you’ll see the key’s secret. This is what you’ll use to access Fauna from Node. Store it somewhere safe as Fauna will never show it to you again.

Preparing our data

We’re now ready to execute our first FQL queries to create our first collection and index. To do this, we’re going to use the shell right from the dashboard:

First, we need a collection to store the documents for our users. To create the Users collection, run this query in the shell:

Next, we need an index that will allow us to ensure unique usernames:

We’re good for now. Let’s go back to our code.

Installing Nodemon and Dotenv

Before continuing to work on our API, let’s install Nodemon and dotenv in our development dependencies:

Nodemon will automatically restart our server whenever we make any changes to our JavaScript code.

Dotenv will allow us to inject environment variables into our server from a .env text file. Sensitive data such as API keys should never be hardcoded into our code or pushed to a Git repository.

Create a .env file in your project folder with this format:

Obviously, use the secret you obtained when creating a server key.

The variables we define in our .env file will be available as environment variables in our code. For example, to access our server secret we will use:

To prevent the .env file and node_modules folder to be pushed to our Git repository, create a .gitignore file with this:

Let’s now add a new script into our package.json:

We now only need to use this command to start our server with Nodemon and dotenv:

Creating a custom error class

Before we start working on our server routes, we need to be prepared to receive errors from Fauna. For this, we will create a custom FaunaError class that can be easily integrated into Fastify’s error handling flow.

This class simply determines the HTTP status and description from the error returned by Fauna. You can customize this later on with more errors or add your own error messages. The statusCode property will be read by Fastify and returned as the HTTP code of the response.

Creating users

Let’s create our first Fastify route which will allow us to create users.

Don’t forget to use the command we previously created to start our server:

First we need to add this line in our index.js file before actually starting our server:

See the index.js file in the repository for the exact location.

Now create the file routes/create-user.js in your project folder with this code:

Since this is a public route, we’re using our server secret to be able to execute queries.

Once our users have logged in, we will be using their own secret to execute queries. A user will only be able to perform the actions we have allowed in our authorization rules. More on this later.

Note that unlike other database clients, we are going to instantiate a new client on every request. We can safely do that because each query is simply an HTTP request, and the Fauna client is a very lightweight wrapper on top of the HTTP engine.

If for any reason Fauna returned an error, we’d only need to catch it and throw a new instance of our FaunaError class. Fastify will take care of the rest.

To test this route we can use any HTTP client. I will be using Postman (which you can download here) but you can use whatever you’re most comfortable with (eg: cURL, Insomnia, etc).

Let’s make a POST request to:

With this body:

Don’t forget to add the Content-Type header:

If everything worked as expected, in the response’s body there should be a JSON representation of the document we just created in the Users collection:

If you’re feeling mischievous you could try sending wrong requests and see how Fastify’s validation reacts. For example, try to create a user without a password, or a password shorter than 10 characters.

You could also try to create the same user twice and see how a Fauna error is returned. Our Users_by_username index will not allow two documents with the same username.

Authenticating users

Let’s now create an endpoint to authenticate our users. First add this to the index.js file:

Also create the file routes/login.js with this:

As you can see, we’re using our Users_by_username index with the Login() function. To understand better how this works, check this article I wrote about authentication and authorization with Fauna.

Let’s try this out by making a POST request to:

With this body:

Our API should return this response with the user’s secret:

At this point, our client should store the secret somewhere and use it to make further requests to our API. We’ll see how this works in the next route.

Beware, for simplicity’s sake we’re using a very basic form of authentication. You should decide very carefully which authentication strategy will work better for your use case and always use HTTPS when interacting with your servers.

Retrieving a user

Let’s now create an endpoint to be able to read a single user. Unlike the previous routes, this is going to be a private route.

Private hook

The best way to solve private routes in Fastify is using a hook. Hooks are custom bits of code that can be triggered at certain points in the request/response flow. Check the Fastify docs for more info on how to use them.

Our hook will check for the presence of a fauna-secret header on the routes we’ve marked as private. We also need to create a decorator to let Fastify know we will be modifying the request object.

Add this to our index.js file:

We don’t really need to validate the secret. Fauna will return an error if we’re using an invalid secret.

The route

Add this to the index.js file:

Also create the routes/get-user.js file with this:

We’ve added the isPrivate property in the config section of the route to mark this route as private for our hook.

Also note that we’re now using the user provided secret to communicate with Fauna (added to the request object in our hook). Our user will now be subjected to the Fauna authorization rules instead of using the omnipotent server secret.

If you now try this route you will get an error because our user does not have permission to read the Users collection.

Let’s create a new custom role in Fauna to solve this.

Setting up authorization in Fauna

It’s also possible to configure authorization rules exclusively using the shell and FQL queries, but for this tutorial we will be using the dashboard.

Go to the Security section of the dashboard, open the Roles tab, and click on New Custom Role.

Give it the name of User, add the Users collection, and click on the Read permission:

We also need to tell Fauna who belongs to this role.

Go to the Membership tab and select the Users collection as a member of this role:

Click save and we’re done.

Basically we’ve told Fauna that anyone logged in with a token based on a document from the Users collection can now read any document in the Users collection.

You can read the authorization article I mentioned earlier to understand better how this works.

Testing our route

I’m going to use the document id 283319645586326016 of the user I created previously. You can check the id of your users’ documents in the Collections section of the dashboard.

Before making the request, be sure to add the user’s secret (the one you got after logging in) into a custom fauna-secret HTTP header:

Now do a GET request to:

You should get your document back:

Deleting a user

Deleting is very similar to reading a user.

First, we will need to add the Delete permission to the User custom role:

Don’t forget to save after modifying the role permissions.

Second, add the route to index.js :

Finally create the routes/delete-user.js file with this:

To test this, make a DELETE request to:

You should get the deleted document back.

An important point to mention is that any authentication tokens based on the deleted document will now be invalid. If you try to use any secret for the deleted user you will get a 401 error.

Setting up fine-grained permissions

There’s one last thing we need to take care of. Our authorization rules are way too permissive and allow any user to read and delete any other user in the Users collection. To fix this we’re going to set up fine-grained permissions so that a user can only read and delete itself.

Go back to your custom role in the dashboard. In the Privileges tab open the dropdown of Users collection. This will reveal extra options for the permissions on this collection.

Now click on the </> symbol under the Read permission which will open a small FQL editor:

Although you could write very complex FQL logic here, for now simply paste this:

We’re defining an anonymous FQL function that will return true if the logged in user is the same as the document we want to read. If it isn’t, it will return false and access will not be granted.

Do the same for the Delete permission and click save for the custom role.

To test this simply log in with a second user and try to read or delete the first user. Your API should now return a 403 error:


If you’ve made it this far, good job!

Here are some articles you could check to keep on learning about Fauna:

Getting started with FQL

Core FQL concepts

Thanks for reading and, as always, if you have any questions don’t hesitate to hit me up on Twitter: @pierb

Author: Pier Bover
Date: December 10, 2020
Originally published at



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Fauna Inc

Fauna is a distributed document-relational database delivered as a cloud API.