# Use TypeDB from Vercel and Next.js

This guide shows how to query TypeDB Cloud from a Next.js app deployed on Vercel. You’ll connect over TypeDB’s HTTP API with the `@typedb/driver-http` package, read data in a Vercel server component, and write it from a Vercel server action.

## [](#_prerequisites)Prerequisites

*   Node.js 22 or later
    
*   A Vercel account
    
*   A TypeDB Cloud cluster. A free cluster is enough: [sign up](https://cloud.typedb.com) and create one.
    

From the cluster page in TypeDB Cloud, note down:

*   the cluster’s **HTTP address**, for example `[https://<cluster>.cloud.typedb.com:8000](https://<cluster>.cloud.typedb.com:8000)`
    
*   a **username** and **password**, which you will set after creating the cluster
    

The finished app is in [typedb-examples/vercel](https://github.com/typedb/typedb-examples/tree/master/vercel). It’s a small directory of people and the topics they’re interested in. If you want an explanation of the source code, keep reading. Otherwise, to get straight to running the app skip to \[Step 7\](#step-7:-deploy-typedb).

## [](#_step_1_create_the_project)Step 1: Create the project

Clone the example, or create a new Next.js app and add the driver:

```sh
npx create-next-app@latest typedb-nextjs --typescript --app
cd typedb-nextjs
npm install @typedb/driver-http@3.15.0
```

Put your connection details in `.env.local`:

```sh
TYPEDB_ADDRESS=https://<cluster>.cloud.typedb.com:8000
TYPEDB_USERNAME=admin
TYPEDB_PASSWORD=<your password>
TYPEDB_DATABASE=vercel_demo
```

None of these variables start with `NEXT_PUBLIC_`, so Next.js never sends them to the browser.Keep it that way.

## [](#_step_2_define_the_schema)Step 2: Define the schema

The data model has people, topics, and an `interest` relation that connects them.Save it as `typedb/schema.tql`:

```typeql
#!test[schema]
define

attribute name, value string;
attribute created-at, value datetime;

entity person,
  owns name @key,
  owns created-at,
  plays interest:fan;

entity topic,
  owns name @key,
  plays interest:subject;

relation interest,
  relates fan,
  relates subject;
```

`@key` makes `name` unique, so TypeDB rejects a second person with the same name.You’ll use that to handle duplicates in \[Step 5\](#step-5-write-from-a-server-action).

You’ll also want some starting data. `typedb/seed.tql` inserts a few people and topics:

```typeql
#!test[write]
insert
  $ada isa person, has name "Ada", has created-at 2025-01-10T09:00:00;
  $compilers isa topic, has name "Compilers";
  interest (fan: $ada, subject: $compilers);
  # …
```

## [](#_step_3_create_the_connection_module)Step 3: Create the connection module

All TypeDB access goes through one server-only module, `lib/typedb.ts`. It creates the driver and wraps the calls the app needs.

```typescript
import {
  TypeDBHttpDriver, isApiError, isApiErrorResponse,
  type ApiResponse, type ConceptDocument, type GivenRows,
} from "@typedb/driver-http";

function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable ${name}.`);
  return value;
}

export const database = process.env.TYPEDB_DATABASE || "vercel_demo";

let driver: TypeDBHttpDriver | undefined;

export function getDriver(): TypeDBHttpDriver {
  driver ??= new TypeDBHttpDriver({
    username: requireEnv("TYPEDB_USERNAME"),
    password: requireEnv("TYPEDB_PASSWORD"),
    addresses: [requireEnv("TYPEDB_ADDRESS")],
  });
  return driver;
}

export function unwrap<T extends {} | null>(res: ApiResponse<T>): T {
  if (isApiErrorResponse(res)) throw res.err;
  return res.ok;
}

export function errorMessage(e: unknown): string {
  return isApiError(e) || e instanceof Error ? e.message : String(e);
}
```

The driver is a module-scope singleton. A warm function instance reuses it along with its token, so each cold start signs in once and later requests don’t.

Driver methods don’t throw on a server error. They return either `{ ok }` or `{ err, status }`. `unwrap` throws the error as it is, an object with a `code` (such as `CNT9`) and a `message`, which makes the rest of the code simpler. To handle a specific error, catch it with the driver’s `isApiError` and check `e.code`. Because the error isn’t an `Error`, `errorMessage` reads the message from either kind.

TypeDB Cloud uses publicly trusted TLS certificates, so you don’t need any `tls` options.

### [](#_reading_data)Reading data

The `read` helper runs a query in its own read transaction:

```typescript
export async function read(tql: string, given?: GivenRows): Promise<ConceptDocument[]> {
  const res = unwrap(await getDriver().oneShotQuery(tql, false, database, "read", undefined, undefined, given));
  if (res.answerType !== "conceptDocuments") throw new Error(`Expected a fetch query, got ${res.answerType}`);
  return res.answers;
}
```

`read` expects `match … fetch` queries. A `fetch` stage returns JSON documents shaped the way you write them, so you can render the results directly.

### [](#_passing_user_input_safely)Passing user input safely

Never build TypeQL by concatenating user input. Declare the inputs in a `given` stage instead and send the values separately as **given rows**:

```typescript
await read(
  `given $name: string;
   match $p isa person, has name == $name;
   fetch { "name": $p.name };`,
  [{ name: "Ada" }],
);
```

Each row is an object keyed by variable name, without the `$`. TypeDB runs the rest of the query once per row.

> **Note:** On TypeDB versions before 3.15, a plain string given value is parsed as a TypeQL literal and is rejected if it contains a double quote. On those versions, send a typed value instead: `{ kind: "value", valueType: "string", value: name }`.

### [](#_writing_data)Writing data

For writes, the module has two helpers: `write` runs one query and commits it, and `writeAll` runs several queries in one transaction:

```typescript
export async function write(tql: string, given?: GivenRows) {
  return unwrap(await getDriver().oneShotQuery(tql, true, database, "write", undefined, undefined, given));
}

export async function writeAll(steps: { tql: string; given?: GivenRows }[]): Promise<void> {
  const d = getDriver();
  const { transactionId } = unwrap(await d.openTransaction(database, "write"));
  try {
    for (const { tql, given } of steps) unwrap(await d.query(transactionId, tql, undefined, given));
    unwrap(await d.commitTransaction(transactionId));
  } catch (e) {
    await d.closeTransaction(transactionId);
    throw e;
  }
}
```

Use `writeAll` when several queries must commit together or not at all. If any query fails, the transaction is closed without committing.

## [](#_step_4_read_in_a_server_component)Step 4: Read in a server component

`app/page.tsx` is a server component, so it can query TypeDB directly while the page renders:

```typescript
import { errorMessage, read } from "@/lib/typedb";

export const dynamic = "force-dynamic";

type Person = { name: string; topics: { name: string }[] };

export default async function Home() {
  let people: Person[];
  try {
    people = (await read(`
      match $p isa person, has name $n;
      sort $n;
      fetch {
        "name": $n,
        "topics": [
          match interest (fan: $p, subject: $t);
          fetch { "name": $t.name };
        ]
      };
    `)) as Person[];
  } catch (e) {
    return <pre>{errorMessage(e)}</pre>;
  }

  return (
    <ul>
      {people.map((p) => (
        <li key={p.name}>
          {p.name}: {p.topics.map((t) => t.name).join(", ")}
        </li>
      ))}
    </ul>
  );
}
```

The nested `[ match …; fetch …; ]` is a subquery that runs once per person, so each person comes back with their own list of topics in a single round trip:

```json
[
  { "name": "Ada", "topics": [{ "name": "Compilers" }, { "name": "Jazz" }] },
  { "name": "Alan", "topics": [{ "name": "Cryptography" }, { "name": "Graphs" }] }
]
```

`dynamic = "force-dynamic"` makes Next.js query TypeDB on every request instead of once at build time.

## [](#_step_5_write_from_a_server_action)Step 5: Write from a server action

Server actions run on the server, so a form can call one without an API route of your own. `app/actions.ts` adds a person and links the topics they chose:

```typescript
"use server";

import { revalidatePath } from "next/cache";
import { isApiError } from "@typedb/driver-http";
import { writeAll } from "@/lib/typedb";

export type ActionResult = { ok: true } | { ok: false; error: string };

export async function addPerson(name: string, topics: string[]): Promise<ActionResult> {
  name = name.trim();
  if (!name) return { ok: false, error: "Name is required." };

  const createdAt = new Date().toISOString().replace("Z", ""); // `datetime` has no time zone

  try {
    await writeAll([
      {
        tql: `given $name: string, $at: datetime;
              insert $p isa person, has name == $name, has created-at == $at;`,
        given: [{ name, at: createdAt }],
      },
      ...(topics.length > 0
        ? [{
            tql: `given $name: string, $topic: string;
                  match $p isa person, has name == $name;
                        $t isa topic, has name == $topic;
                  insert interest (fan: $p, subject: $t);`,
            given: topics.map((topic) => ({ name, topic })),
          }]
        : []),
    ]);
  } catch (e) {
    if (isApiError(e) && e.code === "CNT9") return { ok: false, error: `"${name}" already exists.` };
    console.error(e);
    return { ok: false, error: "Could not save to TypeDB." };
  }

  revalidatePath("/");
  return { ok: true };
}
```

Some things to note:

*   **There are two queries in one transaction.** The first inserts the person. The second runs once per chosen topic, with one given row each, and links the person to that topic. `writeAll` commits both or neither, so a failed link never leaves a person without their topics.
    
*   **The second query is skipped when no topics are chosen.** A query with a `given` stage must be sent at least one row.
    
*   **Duplicates become a form error.** A second person with the same name violates the `@key` constraint, and the server reports error code `CNT9`, which the action turns into a friendly message.
    
*   **`revalidatePath("/")`** makes Next.js re-render the list so the new person appears.
    

The form is a small client component that calls the action with `useActionState` and shows any error it returns. See \[`app/add-person-form.tsx`\]([https://github.com/typedb/typedb-examples/blob/master/vercel/app/add-person-form.tsx](https://github.com/typedb/typedb-examples/blob/master/vercel/app/add-person-form.tsx)) in the example.

## [](#_step_6_set_up_the_database)Step 6: Set up the database

Before the app can run, the database needs to exist, with the schema applied and the seed data loaded. The example’s `scripts/setup.ts` does this with the same driver:

```typescript
import { readFile } from "node:fs/promises";
import { isApiErrorResponse } from "@typedb/driver-http";
import { database, getDriver, unwrap, write } from "../lib/typedb";

const driver = getDriver();

const existing = await driver.getDatabase(database);
if (isApiErrorResponse(existing)) {
  if (existing.status !== 404) unwrap(existing);
  unwrap(await driver.createDatabase(database));
}

const schema = await readFile(new URL("../typedb/schema.tql", import.meta.url), "utf8");
unwrap(await driver.oneShotQuery(schema, true, database, "schema"));

const anyone = unwrap(await driver.oneShotQuery("match $p isa person; limit 1;", false, database, "read"));
if (anyone.answerType === "conceptRows" && anyone.answers.length === 0) {
  await write(await readFile(new URL("../typedb/seed.tql", import.meta.url), "utf8"));
}
```

Add it to `package.json`:

```json
"scripts": {
  "db:setup": "tsx --env-file-if-exists=.env.local scripts/setup.ts"
}
```

## [](#_step_7_deploy_typedb_step_7_deploy_typedb)Step 7: Deploy TypeDB {#step-7:-deploy-typedb}

For this step, you’ll need a running TypeDB instance (version 3.15 or later). You can run \[Community Edition\]([https://typedb.com/docs/home/install/ce/](https://typedb.com/docs/home/install/ce/)) for local development, and self-host or launch on \[TypeDB Cloud\]([https://cloud.typedb.com](https://cloud.typedb.com)) for the real deployment.

Once launched you’ll need to run the setup script in order to initialize the schema and load the starter data. Make sure to fill out `.env.local` with the appropriate values for your deployment.

```sh
cp .env.example .env.local   # fill in the four TYPEDB_* values
npm i
npm run db:setup             # creates the database, applies the schema, loads the seed data
```

The `db:setup` script is designed to be idempotent:

*   It creates the database only if `getDatabase` returns a 404\\.
    
*   It applies the schema with a one-shot `"schema"` query and `commit = true`. `define` is idempotent, so applying an unchanged schema again does nothing.
    
*   It loads the seed data only if there are no people yet.
    

To verify your database setup, you can run `npm run dev` to run the site locally \\- then you can open \[http\\://localhost:3000\]([http://localhost:3000](http://localhost:3000)) and you should see the seed people and their topics. Add a person, reload the page, and they’re still there.

## [](#_step_8_deploy_to_vercel)Step 8: Deploy to Vercel

1.  Push the project to GitHub and import it in Vercel, or use the example’s \[**Deploy** button\]([https://github.com/sam-butcher/typedb-examples/blob/vercel/vercel/README.md](https://github.com/sam-butcher/typedb-examples/blob/vercel/vercel/README.md)).
    
2.  Under **Settings → Environment Variables**, add `TYPEDB_ADDRESS`, `TYPEDB_USERNAME`, `TYPEDB_PASSWORD` and `TYPEDB_DATABASE`. The Deploy button asks for them when you create the project.
    
3.  If your deployment uses a different cluster or database from your local setup, run `npm run db:setup` against it once from your machine. Vercel builds don’t run the setup script.
    
4.  Open the deployment. The example also has `/api/health`, which returns `{"ok":true,"typedb":{…}}` when the app can reach your cluster.
    

## [](#_production_notes)Production notes

Once you’ve got the app up-and-running, you can work on modifying it or creating your own app using Vercel and TypeDB. Make sure to keep these notes in mind to keep your app secure and performant.

*   **Keep TypeDB access on the server.** To prevent credentials from being leaked to clients, query TypeDB only from server components, route handlers and server actions. Never import `lib/typedb.ts` into a `"use client"` file. If you want the build to fail when that happens, add `import "server-only";` at the top of the module.
    
*   **Prefer one-shot queries.** One-shot queries keep each transaction inside a single HTTP call, which fits serverless well. Use an explicit transaction, as in `writeAll`, only when several queries must commit together.
    
*   **Choose a region.** When selecting your Vercel and TypeDB regions (through Settings → Functions → Region on Vercel, and while deploying your cluster in TypeDB), make sure to place them as close to each other as possible. Each query is an HTTPS round trip, so distance adds directly to latency.
    
*   **Using runtimes other than Node.js.** The pages use the default Node.js runtime. The driver depends only on `fetch`, so it also runs on Edge-style runtimes such as middleware or Cloudflare Workers. If you use one, leave the driver’s `tls.rootCAPath` option unset, because it needs Node’s `https` module.
    

## [](#_troubleshooting)Troubleshooting

 

Symptom

Likely cause

`Missing environment variable TYPEDB_…` when deploying through Vercel

The variable isn’t set for this environment. In Vercel, check that it’s set for Production **and** Preview.

`[SRV3] Database '…' not found` when opening the app

The database doesn’t exist. Run `npm run db:setup` against this cluster.

`[GVN3] An error occured while parsing the provided value` when inserting a user

The server is older than 3.15 and a plain string given value contains a `"`. Upgrade, or send a typed value (see \[Passing user input safely\](#passing-user-input-safely)).

## [](#_next_steps)Next steps

[TypeQL reference](../../../typeql-reference/index.md)

Learn more TypeQL, including pipelines, `fetch`, and `given`

[TypeDB HTTP API reference](../../../reference/typedb-http-api/index.md)

See every endpoint the driver wraps

[TypeScript HTTP driver reference](../../../reference/typedb-http-drivers/typescript/index.md)

See the full documentation for the TypeScript HTTP driver

[TypeDB MCP server](../../../tools/mcp-server/index.md)

Let an AI assistant query the same database

[AI Agents persistence with LangGraph and TypeDB](../langgraph/index.md) [TypeQL](../../typeql/index.md)

[Edit on GitHub](https://github.com/typedb/typedb-docs/edit/3.x-development/guides/modules/ROOT/pages/integrations/vercel.adoc) Edit this page on GitHub.