PlanetScale
Create a new TypeScript project from scratch by connecting Prisma ORM to PlanetScale MySQL and generating a Prisma Client for database access.
PlanetScale is a serverless database platform. This guide covers PlanetScale MySQL. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PlanetScale MySQL using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database.
PlanetScale also offers PostgreSQL databases. If you're using PlanetScale PostgreSQL, follow the PostgreSQL quickstart guide instead.
Prerequisites
You also need:
- A PlanetScale database
- Database connection string from PlanetScale
1. Create a new project
2. Install required dependencies
Install the packages needed for this quickstart:
npm install prisma @types/node --save-devnpm install @prisma/client @prisma/adapter-planetscale undici dotenvHere's what each package does:
prisma- The Prisma CLI for running commands likeprisma init,prisma migrate, andprisma generate@prisma/client- The Prisma Client library for querying your database@prisma/adapter-planetscale- The PlanetScale driver adapter that connects Prisma Client to your databaseundici- A fast HTTP/1.1 client required by the PlanetScale adapterdotenv- Loads environment variables from your.envfile
3. Configure ESM support
Update tsconfig.json for ESM compatibility:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}Update package.json to enable ESM:
{
"type": "module"
}4. Initialize Prisma ORM
You can now invoke the Prisma CLI by prefixing it with npx:
npx prismaNext, set up your Prisma ORM project by creating your Prisma Schema file with the following command:
npx prisma init --datasource-provider mysql --output ../generated/prismaThis command does a few things:
- Creates a
prisma/directory with aschema.prismafile containing your database connection and schema models - Creates a
.envfile in the root directory for environment variables - Creates a
prisma.config.tsfile for Prisma configuration
The generated prisma.config.ts file looks like this:
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"),
},
});The generated schema uses the ESM-first prisma-client generator with a custom output path:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "mysql"
}Update your schema to include relationMode = "prisma" for PlanetScale:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "mysql"
relationMode = "prisma"
}Update your .env file with your PlanetScale connection string:
DATABASE_URL="mysql://username:password@host.connect.psdb.cloud/mydb?sslaccept=strict"Replace with your actual PlanetScale connection string from your database dashboard.
5. Define your data model
Open prisma/schema.prisma and add the following models:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "mysql"
relationMode = "prisma"
}
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? @db.Text
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
@@index([authorId])
} Note the @@index([authorId]) on the Post model. PlanetScale requires indexes on foreign keys when using relationMode = "prisma".
6. Push your schema to PlanetScale
PlanetScale uses a branching workflow instead of traditional migrations. Push your schema directly:
npx prisma db pushThis command creates the database tables based on your schema.
Now run the following command to generate the Prisma Client:
npx prisma generate7. Instantiate Prisma Client
Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the PrismaClient constructor:
import "dotenv/config";
import { PrismaPlanetScale } from "@prisma/adapter-planetscale";
import { PrismaClient } from "../generated/prisma/client";
import { fetch as undiciFetch } from "undici";
const adapter = new PrismaPlanetScale({ url: process.env.DATABASE_URL, fetch: undiciFetch });
const prisma = new PrismaClient({ adapter });
export { prisma };8. Write your first query
Create a script.ts file to test your setup:
import { prisma } from "./lib/prisma";
async function main() {
// Create a new user with a post
const user = await prisma.user.create({
data: {
name: "Alice",
email: "alice@prisma.io",
posts: {
create: {
title: "Hello World",
content: "This is my first post!",
published: true,
},
},
},
include: {
posts: true,
},
});
console.log("Created user:", user);
// Fetch all users with their posts
const allUsers = await prisma.user.findMany({
include: {
posts: true,
},
});
console.log("All users:", JSON.stringify(allUsers, null, 2));
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});Run the script:
npx tsx script.tsYou should see the created user and all users printed to the console!
9. Explore your data with Prisma Studio
Prisma Studio is a visual editor for your database. Launch it with:
npx prisma studioThis opens a web interface where you can view and edit your data.
Supported databases
Prisma Studio currently supports PostgreSQL, MySQL, and SQLite. For more details, see Databases supported by Prisma Studio.