FaunaDB with Next.js

May 06, 2021

2 min read

— views

Setup a Next.js project with TypeScript and FaunaDB.

Requirements

  • A FaunaDB account and a key from the security settings of your database.
  • NodeJS & npm

Creating the project

First we'll need to create the project. Let's create a new folder called nextjs-faunadb.

mkdir nextjs-faunadb && cd nextjs-faunadb
bash

Secondly, we need to init the npm project.

npm init -y
bash

Now we'll install the required dependencies.

npm install react react-dom next faunadb
 
# typings for react and react-dom. Next.js and FaunaDB have their own typings šŸŽ‰
npm install @types/react @types/react-dom typescript --save-dev
bash

Lastly we'll create the tsconfig. Don't worry about the contents, Next.js will overwrite it with the correct configuration.

tsc --init
bash

Folder structure

Once that has all finished installing, we can create the folder structure as seen below.

ā”œā”€ā”€ pages
ā”œā”€ā”€ ā”œā”€ā”€ api
ā”œā”€ā”€ ā”œā”€ā”€ ā”œā”€ā”€ index.ts
│   ā”œā”€ā”€ index.tsx
ā”œā”€ā”€ lib
│   ā”œā”€ā”€ faunadb.ts
│
ā”œā”€ā”€ package.json
└── ...
txt

Creating the faunadb client

In the lib/faunadb.ts file we created above, we will create and export the client. I recommend adding a .env file with the following contents:

.env
FAUNADB_KEY="KEY_HERE"
txt

lib/faunadb.ts
import { Client } from "faunadb";
 
if (!process.env.FAUNADB_KEY) {
  throw new Error("`FAUNADB_KEY` must be provided in the `.env` file");
}
 
export const client = new Client({ secret: process.env.FAUNADB_KEY });
tsx

Using the client in our API

Bellow you can see how to use the client in your api pages.

pages/api/index.ts
import { NextApiRequest, NextApiResponse } from "next";
import { client } from "../../lib/faunadb";
 
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
    case "GET": {
      const items = await client.query(/* ... */);
 
      return res.json({
        items,
        status: "success",
      });
    }
 
    case "POST": {
      const { name } = req.body;
 
      const doc = await client.query(/* ... */);
 
      return res.json({
        status: "success",
      });
    }
 
    default: {
      return res.status(405).json({
        status: "error",
        error: "Method not allowed",
      });
    }
  }
}
tsx

Documentation

You can check the FaunaDB documentation here šŸš€

Examples

I have 2 FaunaDB and Next.js projects in my GitHub repositories tab that you can use as a reference/an example šŸ˜„