Node.js quick start
Use Fauna’s JavaScript driver to query e-commerce demo data in a Node.js app. The app requires Node.js v18 or later and npm.
-
Create a database with demo data
Log in to the Fauna Dashboard, and create a database with the following configuration:
-
Region group: Choose your preferred region group, which determines where your data resides.
-
Use demo data: Enabled.
-
Enable backups: Disabled.
Leave the other options as is.
-
-
Create an authentication secret
Fauna supports several types of authentication secrets. Create a key, which is a type of secret, with the built-in
server-readonly
role:-
In the Dashboard’s Explorer page, select your demo database.
-
In the database’s Keys tab, click Create Key.
-
Choose a Role of server (read-only).
-
Click Save.
-
Copy the Key Secret.
-
-
Set the FAUNA_SECRET environment variable
Set the
FAUNA_SECRET
environment variable to your key’s secret. Fauna’s client drivers can access the secret from this variable.export FAUNA_SECRET=<KEY_SECRET>
-
Install the JavaScript driver
Create a new directory for your app and install the JavaScript driver:
mkdir app cd app npm install fauna
-
Create a basic app
In the
app
directory, create anapp.mjs
file and add the following code:import { Client, fql, FaunaError } from "fauna"; // Use `require` for CommonJS: // const { Client, fql, FaunaError } = require('fauna'); // Initialize the client to connect to Fauna // using the `FAUNA_SECRET` environment variable. const client = new Client(); try { // Compose a query using an FQL template string. // The query calls the `Product` collection's // `sortedByPriceLowToHigh()` index. It projects the `name`, // `description`, and `price` fields covered by the index. const query = fql` Product.sortedByPriceLowToHigh() { name, description, price }`; // Run the query. const pages = client.paginate(query); // Iterate through the results. const products = []; for await (const product of pages.flatten()) { products.push(product); } console.log(products); } catch (error) { if (error instanceof FaunaError) { console.log(error); } } finally { client.close(); }
-
Run the app
Run the script from the
app
directory. The script prints a list of e-commerce products from the demo data in the terminal.node app.mjs