FaunaDB with Next.js

May 06, 2021

2 min read


Setup a Next.js project with TypeScript and FaunaDB.


  • 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

Secondly, we need to init the npm project.

npm init -y

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

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

tsc --init

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
└── ...

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:


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 });

Using the client in our API

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

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({
        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",


You can check the FaunaDB documentation here 🚀


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