FaunaDB with Next.js

Created: 2021-05-06 - 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

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

While the dependencies are installing we can create the folder structure.

ā”œā”€ā”€ pages
ā”œā”€ā”€ ā”œā”€ā”€ api
ā”œā”€ā”€ ā”œā”€ā”€ ā”œā”€ā”€ hello.ts
ā”‚   ā”œā”€ā”€ index.tsx
ā”œā”€ā”€ lib
ā”‚   ā”œā”€ā”€ faunadb.ts
ā”‚
ā”œā”€ā”€ package.json
ā””ā”€ā”€ ...

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:

FAUNADB_KEY="KEY_HERE"
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 });

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

// pages/api/hello.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",
      });
    }
  }
}

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 šŸ˜„