Navigation

Using PlanetScale with Prisma

Prisma ORM provides type-safe database access through an intuitive API, eliminating the need to write SQL queries manually. Prisma and PlanetScale together offer a powerful workflow. Prisma handles the object-relational mapping with full type safety and intuitive data modeling, while PlanetScale provides horizontal scaling, branching workflows, and zero-downtime schema changes, making it an ideal stack for building modern, scalable applications.

This guide covers how to use Prisma and PlanetScale together, including how to:

  • Create a database with PlanetScale
  • Integrate it with Prisma
  • Use additional features like sharding and the serverless driver

If you don't already have an application set up with Prisma, but want to test how it works with PlanetScale, we recommend grabbing a sample application from Prisma's examples repository.

Set up your PlanetScale database

First, set up your PlanetScale database.

  1. Sign in to your PlanetScale account
  2. Click "Create a database"
  3. Give your database a name
  4. Select your preferred region
  5. Choose cluster and storage size
  6. Click "Create database"

Your database will deploy with an initial production branch, main.

Create a password

After the database is created, you'll be prompted to generate credentials for it. You can come back to this later if needed.

  1. Give your password a name or leave the default
  2. Select a password role. We recommend Admin for your default password.
  3. Click "Create password"
  4. Select "Prisma" for "Select your language or framework"
  5. Do not navigate away from this page. The next section covers where to paste these credentials in your Prisma app. If you close without copying, you can regenerate new credentials.

Connect to PlanetScale in your application

Next, add your database credentials to your Prisma application. If you are migrating an existing database to PlanetScale, you can test the PlanetScale/Prisma integration locally or in staging first. Once you're ready to migrate the database from your existing provider, refer to our no downtime migration guides.

To connect PlanetScale to your Prisma application:

  1. Follow the steps in the above section if you navigated away from the page previously
  2. Update your prisma/schema.prisma file with the following:
    datasource db {
      provider     = "mysql"
      url          = env("DATABASE_URL")
      relationMode = "prisma"
    }
    
  3. Update the DATABASE_URL value in your .env file with the value provided to you when you created a new password in the PlanetScale dashboard. It should look like this:
DATABASE_URL='mysql://<USERNAME>:<PASSWORD>@aws.connect.psdb.cloud/<DATABASE>?sslaccept=strict'

Foreign key constraints

PlanetScale does not enable foreign key constraints by default. If you are not using foreign key constraints to enforce referential integrity at the database level, integrating with Prisma will still work, but it requires a couple additional steps (detailed below).

If you do plan to use foreign key constraints, enable them on your PlanetScale database settings page.

  1. In your database dashboard, go to "Settings"
  2. Enable "Foreign key constraints"
  3. Save your changes

Using Prisma without foreign key constraints

If you are not using foreign key constraints, you can use Prisma's relationMode to emulate relations.

You need to update datasource db in your schema.prisma file to include relationMode = "prisma":

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

When emulating relations, you also need to manually create dedicated indexes on foreign keys to avoid performance issues. For example, if you have Post and Comment tables, where the Comment table references a post, you need to add an index to your Post model:

model Post {
  id       Int       @id @default(autoincrement())
  title    String
  content  String
  likes    Int       @default(0)
  comments Comment[]
}

model Comment {
  id      Int    @id @default(autoincrement())
  comment String
  postId  Int
  post    Post   @relation(fields: [postId], references: [id], onDelete: Cascade)

  @@index([postId]) // manually created index
}

You can learn more about how to do this in Prisma in their Emulating relations documentation.

Push your Prisma schema to PlanetScale

Push your schema to your PlanetScale branch with:

npx prisma db push

The recommended workflow with using Prisma alongside PlanetScale is to use prisma db push instead of prisma migrate. You can read more about prisma db push here.

Your PlanetScale database schema now matches the Prisma schema you configured in prisma/schema.prisma. To confirm this, go to your PlanetScale dashboard, click "Branches", and select the branch you generated credentials for. You should see your schema.

Using the PlanetScale serverless driver with Prisma

The PlanetScale serverless driver allows you to execute queries over HTTP. You can use it with Prisma ORM via the @prisma/adapter-planetscale driver adapter. This adapter is available in Preview from Prisma ORM versions 5.4.2 and later.

  1. Enable the driverAdapters Preview feature in your Prisma schema:
    generator client {
      provider        = "prisma-client-js"
      previewFeatures = ["driverAdapters"]
    }
    
  2. Generate Prisma Client:
    npx prisma generate
    
  3. If you're not already using a direct connection string, update your host to aws.connect.psdb.cloud or gcp.connect.psdb.cloud, depending on your chosen region.
  4. Install the Prisma adapter-planetscale and PlanetScale serverless driver packages:
    npm install @prisma/adapter-planetscale @planetscale/database undici
    
  5. Configure your Prisma Client with the adapter:
    import { PrismaPlanetScale } from '@prisma/adapter-planetscale'
    import { PrismaClient } from '@prisma/client'
    import dotenv from 'dotenv'
    import { fetch as undiciFetch } from 'undici'
    
    dotenv.config()
    const connectionString = `${process.env.DATABASE_URL}`
    
    const adapter = new PrismaPlanetScale({ url: connectionString, fetch: undiciFetch })
    const prisma = new PrismaClient({ adapter })
    

For more information, see the Prisma documentation.

Sharding with PlanetScale and Prisma

If you are using a sharded database with PlanetScale, Prisma supports defining shard keys in your Prisma schema. This is currently available as a Preview feature in Prisma as of v6.10.0.

To use shard key attributes, specify the shardKeys Preview feature on your Prisma generator in schema.prisma:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["shardKeys"]
}

This allows you to use @shardKey and @@shardKey attributes.

  • @shardKey — Used to define a single-column shard key
  • @@shardKey — Used to define a multi-column shard key

For example, if you have a shard key on your region column in your User database, you can define that in your Prisma model with:

model User {
  id     String @default(uuid())
  region String @shardKey
}

Next steps

Additional resources

Need help?

Get help from the PlanetScale Support team, or join our GitHub discussion board to see how others are using PlanetScale.