Skip to content
How-to
6 min read

Using an ORM to access your Postgres database

Learn how to use your favorite ORM to access your database from your apps
Table of Contents
Choose a framework to optimize documentation to:

    Vercel Postgres is available on Hobby and Pro plans

    Vercel Postgres provides an SDK, but we recommend using an ORM for larger applications.

    To get started using Vercel Postgres with your favorite ORM, follow the instructions in our Postgres quickstart.

    If your ORM is featured on this page, read the corresponding section for the most optimal configuration instructions.

    Kysely is a type-safe and autocomplete-friendly TypeScript SQL query builder. Use our Kysely template to deploy a Next.js project that connects to Vercel Postgres with Kysely now.

    To use Kysely, follow these steps:

    1. Install the Kysely package:

      pnpm
      yarn
      npm
      pnpm i kysely @vercel/postgres-kysely
    2. Use the createKysely method from @vercel/postgres-kysely to create a client with a pooled connection

      import { createKysely } from '@vercel/postgres-kysely';
       
      interface Database {
        person: PersonTable;
        pet: PetTable;
        movie: MovieTable;
      }
       
      const db = createKysely<Database>();
       
      await db
        .insertInto('pet')
        .values({ name: 'Catto', species: 'cat', owner_id: id })
        .execute();
       
      const person = await db
        .selectFrom('person')
        .innerJoin('pet', 'pet.owner_id', 'person.id')
        .select(['first_name', 'pet.name as pet_name'])
        .where('person.id', '=', id)
        .executeTakeFirst();

    Kysely supports all PostgreSQL commands. See Kysely's docs for a full reference of the methods used to send the commands.

    Prisma is a next-gen ORM that includes a type-safe query builder, migration system, and database management interface. Use our Prisma template to deploy a Next.js project that connects to Vercel Postgres with Prisma now.

    To use Vercel Postgres with Prisma, you must:

    1. Follow the instructions in our Postgres quickstart

    2. Install Prisma client and Prisma CLI:

      pnpm
      yarn
      npm
      pnpm i prisma @prisma/client
    3. Use your environment variables in your schema.prisma file as shown below:

      schema.prisma
      generator client {
        provider = "prisma-client-js"
      }
       
      datasource db {
        provider = "postgresql"
        url = env("POSTGRES_PRISMA_URL") // uses connection pooling
        directUrl = env("POSTGRES_URL_NON_POOLING") // uses a direct connection
      }
       
      model User {
        id        Int      @id @default(autoincrement())
        name      String
        email     String   @unique
        image     String
        createdAt DateTime @default(now())
      }
    4. Use @prisma/client to query your Vercel Postgres database

      import { PrismaClient } from '@prisma/client';
       
      const prisma = new PrismaClient();
       
      export default async function prismaExample() {
        const newUser = await prisma.user.create({
          data: {
            name: 'Elliott',
            email: 'xelliottx@example-user.com',
          },
        });
       
        const users = await prisma.user.findMany();
      }
    5. Whenever you make changes to your prisma schema, you must run a migration, then run prisma generate to update the generated type generations, which live in the node_modules/.prisma/client directory.

      Prisma generate
      prisma generate

    When you connect with Prisma using the POSTGRES_PRISMA_URL environment variable, the parameters connect_timeout=10 and pgbouncer=true will be set.

    See the Prisma docs to learn more.

    See the Prisma Migrate docs to migrate your database.

    Drizzle is a TypeScript ORM that enables developers to build type-safe SQL queries. It relies on zero dependencies, and uses a SQL-like syntax to offer a lower learning curve than other ORMs. Use our Drizzle template to deploy a Next.js project that connects to Vercel Postgres with Drizzle now.

    To use Drizzle with Vercel Postgres, you must:

    1. Follow the instructions in the Postgres quickstart
    2. Install the drizzle-orm package:
      pnpm
      yarn
      npm
      pnpm i drizzle-orm
    3. Create a client that connects to your Vercel Postgres database with Drizzle:
    simple-connect.ts
    import { drizzle } from 'drizzle-orm/vercel-postgres';
    import { sql } from '@vercel/postgres';
    import {
      pgTable,
      serial,
      text,
      timestamp,
      uniqueIndex,
    } from 'drizzle-orm/pg-core';
     
    // Use this object to send drizzle queries to your DB
    export const db = drizzle(sql);
    // Create a pgTable that maps to a table in your DB
    export const ExampleTable = pgTable(
      'users',
      {
        id: serial('id').primaryKey(),
        name: text('name').notNull(),
        email: text('email').notNull(),
        image: text('image').notNull(),
        createdAt: timestamp('createdAt').defaultNow().notNull(),
      },
      (users) => {
        return {
          uniqueIdx: uniqueIndex('unique_idx').on(users.email),
        };
      },
    );
     
    export const getExampleTable = async () => {
      const selectResult = await db.select().from(ExampleTable);
      console.log('Results', selectResult);
    };
    Last updated on November 30, 2023