This page provides a step-by-step guide for Prisma Postgres after setting it up with `prisma init --db`:

1. Set up a TypeScript app with Prisma ORM
1. Migrate the schema of your database
1. Query your database from TypeScript

## Prerequisites

This guide assumes you set up [Prisma Postgres](/postgres) instance with `prisma init --db`:

<CodeWithResult outputResultText="" expanded={false}>

<cmd>

```terminal
npx prisma@latest init --db
```

</cmd>

<cmdResult>

```code no-copy wrap
✓ Select an authentication method Google
Authenticating to Prisma Platform via browser.

Visit the following URL in your browser to authenticate:
https://console.prisma.io/auth/cli?state=eyJjb6ll...

Successfully authenticated as jon@doe.com.
Let's set up your Prisma Postgres database!
✓ Select your region: ap-southeast-1 - Asia Pacific (Singapore)
✓ Enter a project name: My Prisma Project
✓ Success! Your Prisma Postgres database is ready ✅

We found an existing schema.prisma file in your current project directory.

--- Database URL ---

Connect Prisma ORM to your Prisma Postgres database with this URL:

--- Next steps ---

Go to https://pris.ly/ppg-init for detailed instructions.

1. Install the Postgres adapter
npm install @prisma/adapter-pg

...and add it to your Prisma Client instance:

import { PrismaClient } from "./generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";

const connectionString = `${process.env.DATABASE_URL}`;

const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });

2. Apply migrations
Run the following command to create and apply a migration:
npx prisma migrate dev

3. Manage your data
View and edit your data locally by running this command:
npx prisma studio

...or online in Console:
https://console.prisma.io/$path

4. Send queries from your app
If you already have an existing app with Prisma ORM, you can now run it and it will send queries against your newly created Prisma Postgres instance.

5. Learn more
For more info, visit the Prisma Postgres docs: https://pris.ly/ppg-docs
```

</cmdResult>

</CodeWithResult>

Once this command terminated:

- You're logged into Prisma Data Platform.
- A new Prisma Postgres instance was created.
- The `prisma/` folder was created with an empty `schema.prisma` file.
- The `DATABASE_URL` env var was set in a  `.env` file.
- The `prisma.config.ts` file was created with the default configuration.

## 1. Organize your project directory

:::note

If you ran the `prisma init --db` command inside a folder where you want your project to live, you can skip this step and [proceed to the next section](/getting-started/prisma-postgres/from-the-cli#2-set-up-your-project).

:::

If you ran the command outside your intended project directory (e.g., in your home folder or another location), you need to move the generated `prisma` folder and the `.env` file into a dedicated project directory.

Create a new folder (e.g. `hello-prisma`) where you want your project to live and move the necessary files into it:

```terminal
mkdir hello-prisma
mv .env ./hello-prisma/
mv prisma ./hello-prisma/
```

Navigate into your project folder:

```terminal
cd ./hello-prisma
```

Now that your project is in the correct location, continue with the setup.

## 2. Set up your project

### 2.1. Set up TypeScript

Initialize a TypeScript project and add the Prisma CLI as a development dependency:

```terminal
npm init -y
npm install typescript tsx @types/node @types/pg --save-dev
```

This creates a `package.json` file with an initial setup for your TypeScript app.

Next, initialize TypeScript with a `tsconfig.json` file in the project:

```terminal
npx tsc --init
```

### 2.2. Configure ESM support

Update `tsconfig.json` for ESM compatibility:

```json file=tsconfig.json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2023",
    "strict": true,
    "esModuleInterop": true,
    "ignoreDeprecations": "6.0"
  }
}
```

Update `package.json` to enable ESM:

```json file=package.json
{
  // add-start
  "type": "module",
  // add-end
}
```

### 2.3. Set up Prisma ORM

Install the required dependencies to use Prisma Postgres:

```terminal
npm install prisma --save-dev
npm install @prisma/client @prisma/adapter-pg pg dotenv
```

Here's what each package does:

- **`prisma`** - The Prisma CLI for running commands like `prisma migrate` and `prisma generate`
- **`@prisma/client`** - The Prisma Client library for querying your database
- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database
- **`pg`** - The node-postgres database driver
- **`@types/pg`** - TypeScript type definitions for node-postgres
- **`dotenv`** - Loads environment variables from your `.env` file

### 2.4. Review the generated prisma.config.ts

The `prisma init --db` command automatically created a `prisma.config.ts` file that looks like this:

```typescript file=prisma.config.ts
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: {
    path: 'prisma/migrations',
  },
  datasource: {
    url: env('DATABASE_URL'),
  },
})
```

### 2.5. Create a script to query the database

Create an `index.ts` file in the root directory, this will be used to query your application with Prisma ORM: 

```terminal
touch index.ts
```

## 3. Migrate the database schema

Update your `prisma/schema.prisma` file to include the `User` and `Post` models:

```prisma file=prisma/schema.prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "postgresql"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}
```

After adding the models, migrate your database using [Prisma Migrate](/orm/prisma-migrate):

```terminal
npx prisma migrate dev --name init
```

This command creates the database tables based on your schema.

Now run the following command to generate the Prisma Client:

```terminal
npx prisma generate
```

## 4. Send queries with Prisma ORM

### 4.1. Instantiate Prisma Client

Create a `lib/prisma.ts` file to instantiate Prisma Client with the driver adapter:

```typescript file=lib/prisma.ts
import "dotenv/config";
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/prisma/client'

const connectionString = `${process.env.DATABASE_URL}`

const adapter = new PrismaPg({ connectionString })
const prisma = new PrismaClient({ adapter })

export { prisma }
```

:::tip

If you need to query your database via HTTP from an edge runtime (Cloudflare Workers, Vercel Edge Functions, etc.), use the [Prisma Postgres serverless driver](/postgres/database/serverless-driver#use-with-prisma-orm).

:::

### 4.2. Write your first query

Paste the following boilerplate into `index.ts`:

```ts file=index.ts
import { prisma } from './lib/prisma'

async function main() {
  // ... you will write your Prisma ORM queries here
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
```

This code contains a `main` function that's invoked at the end of the script. It also instantiates `PrismaClient` which you'll use to send queries to your database.

### 4.3. Create a new `User` record

Let's start with a small query to create a new `User` record in the database and log the resulting object to the console. Add the following code to your `index.ts` file:

```ts file=index.ts
import { prisma } from './lib/prisma'

async function main() {
  // add-start
  const user = await prisma.user.create({
    data: {
      name: 'Alice',
      email: 'alice@prisma.io',
    },
  })
  console.log(user)
  // add-end
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
```

Next, execute the script with the following command:

<CodeWithResult expanded={true}>

<cmd>

```terminal
npx tsx index.ts
```
</cmd>

<cmdResult>

```code no-copy
{ id: 1, email: 'alice@prisma.io', name: 'Alice' }
```

</cmdResult>

</CodeWithResult>

Great job, you just created your first database record with Prisma Postgres! 🎉

### 4.4. Retrieve all `User` records

Prisma ORM offers various queries to read data from your database. In this section, you'll use the `findMany` query that returns _all_ the records in the database for a given model.

Delete the previous Prisma ORM query and add the new `findMany` query instead:

```ts file=index.ts
import { prisma } from './lib/prisma'

async function main() {
  // add-start
  const users = await prisma.user.findMany()
  console.log(users)
  // add-end
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
```

Execute the script again:

<CodeWithResult expanded={true}>

<cmd>

```terminal
npx tsx index.ts
```

</cmd>

<cmdResult>

```code no-copy
[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }]
```

</cmdResult>

</CodeWithResult>

Notice how the single `User` object is now enclosed with square brackets in the console. That's because the `findMany` returned an array with a single object inside.

### 4.5. Explore relation queries

One of the main features of Prisma ORM is the ease of working with [relations](/orm/prisma-schema/data-model/relations). In this section, you'll learn how to create a `User` and a `Post` record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the `include` option.

First, adjust your script to include the nested query:

```ts file=index.ts
import { prisma } from './lib/prisma'

async function main() {
  // add-start
  const user = await prisma.user.create({
    data: {
      name: 'Bob',
      email: 'bob@prisma.io',
      posts: {
        create: [
          {
            title: 'Hello World',
            published: true
          },
          {
            title: 'My second post',
            content: 'This is still a draft'
          }
        ],
      },
    },
  })
  console.log(user)
  // add-end
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
```

Run the query by executing the script again:

<CodeWithResult expanded={true}>

<cmd>

```terminal
npx tsx index.ts
```

</cmd>

<cmdResult>

```code no-copy
{ id: 2, email: 'bob@prisma.io', name: 'Bob' }
```

</cmdResult>

</CodeWithResult>

In order to also retrieve the `Post` records that belong to a `User`, you can use the `include` option via the `posts` relation field:

```ts file=index.ts
import { prisma } from './lib/prisma'

async function main() {
// add-start
  const usersWithPosts = await prisma.user.findMany({
    include: {
      posts: true,
    },
  })
  console.dir(usersWithPosts, { depth: null })
  // add-end
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })
```

Run the script again to see the results of the nested read query:

<CodeWithResult expanded={true}>

<cmd>

```terminal
npx tsx index.ts
```

</cmd>

<cmdResult>

```code no-copy
[
  { id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] },
  {
    id: 2,
    email: 'bob@prisma.io',
    name: 'Bob',
    posts: [
      {
        id: 1,
        title: 'Hello World',
        content: null,
        published: true,
        authorId: 2
      },
      {
        id: 2,
        title: 'My second post',
        content: 'This is still a draft',
        published: false,
        authorId: 2
      }
    ]
  }
]
```

</cmdResult>

</CodeWithResult>

This time, you're seeing two `User` objects being printed. Both of them have a `posts` field (which is empty for `"Alice"` and populated with two `Post` objects for `"Bob"`) that represents the `Post` records associated with them.


## Next steps

You just got your feet wet with a basic Prisma Postgres setup. If you want to explore more complex queries, such as [adding caching functionality](/postgres/database/caching#setting-up-caching-in-prisma-postgres), check out the official [Quickstart](/getting-started/prisma-orm/quickstart/prisma-postgres).

### View and edit data in Prisma Studio

Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command:

```terminal
npx prisma studio --config ./prisma.config.ts
```

With Prisma Postgres, you can also directly use Prisma Studio inside the [Console](https://console.prisma.io) by selecting the **Studio** tab in your project. 


### Build a fullstack app with Next.js

Learn how to use Prisma Postgres in a fullstack app:

- [Build a fullstack app with Next.js 15](/guides/nextjs)
- [Next.js 15 example app](https://github.com/prisma/nextjs-prisma-postgres-demo) (including authentication)


### Explore ready-to-run examples

Check out the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more.

These examples use SQLite by default but you can follow the instructions in the project README to switch to Prisma Postgres in a few simple steps.
---

# Use Prisma Postgres with Kysely