Skip to content
25K
Console

PlanetScale

PlanetScale is a cloud database platform built for speed and scalability, with built-in branching. This guide covers how to set it up with SST.

Install

Add the PlanetScale provider to your SST app. Learn more about providers.

Terminal window
sst add planetscale

This adds the provider to your sst.config.ts.

sst.config.ts
{
providers: {
planetscale: "0.4.1",
},
}

Then set the PLANETSCALE_SERVICE_TOKEN and PLANETSCALE_SERVICE_TOKEN_ID environment variables. You can create a service token in the PlanetScale dashboard under Settings > Service tokens.

Features

Reference a database

Reference an existing PlanetScale database directly from your SST config.

sst.config.ts
const db = planetscale.getDatabaseOutput({
name: "mydb",
organization: "myorg",
});

Branch per stage

PlanetScale supports database branching natively. Combined with SST, every stage and every pull request can get its own isolated database branch automatically.

Conditionally create or reference a branch based on the current stage.

sst.config.ts
const branch =
$app.stage === "production"
? planetscale.getBranchOutput({
name: "production",
organization: db.organization,
database: db.name,
})
: new planetscale.Branch("DatabaseBranch", {
database: db.name,
organization: db.organization,
name: $app.stage,
parentBranch: "production",
});

In production, it references the existing production branch. In any other stage, it creates a new branch from production. So sst deploy --stage pr-42 creates a pr-42 branch in PlanetScale.

This is a pattern used in production by terminal.shop and OpenCode.

Usage

Create a password for the branch and wrap it in a sst.Linkable.

sst.config.ts
const password = new planetscale.Password("DatabasePassword", {
database: db.name,
organization: db.organization,
branch: branch.name,
role: "admin",
name: `${$app.name}-${$app.stage}`,
});
export const database = new sst.Linkable("Database", {
properties: {
host: password.accessHostUrl,
username: password.username,
password: password.plaintext,
database: db.name,
port: 3306,
},
});

The Linkable component lets you wrap arbitrary values and make them available to any function or service you link it to. Learn more about linking resources.

Connect to the database

Link the database to any function or service.

sst.config.ts
new sst.aws.Function("Api", {
handler: "src/api.handler",
link: [database],
});

Then access the credentials in a type-safe way through Resource. For example, with Drizzle ORM.

src/drizzle.ts
import { drizzle } from "drizzle-orm/planetscale-serverless";
import { Resource } from "sst";
export const db = drizzle({
connection: {
host: Resource.Database.host,
username: Resource.Database.username,
password: Resource.Database.password,
},
});

You can use any other ORM or database driver the same way.