Skip to content
25K
Console

D1

The D1 component lets you add a Cloudflare D1 database to your app.

Minimal example

sst.config.ts
const db = new sst.cloudflare.D1("MyDatabase");

You can link the db to a worker.

sst.config.ts
new sst.cloudflare.Worker("MyWorker", {
handler: "./index.ts",
link: [db],
url: true
});

Once linked, you can use the SDK to interact with the db.

index.ts
import { Resource } from "sst";
await Resource.MyDatabase.prepare(
"SELECT id FROM todo ORDER BY id DESC LIMIT 1",
).first();

Constructor

new D1(name, args?, opts?)

Parameters

D1Args

transform?

Type Object

Transform how this component creates its underlying resources.

transform.database?

Type D1DatabaseArgs | (args: D1DatabaseArgs, opts: ComponentResourceOptions, name: string) => void

Transform the D1 resource.

Properties

databaseId

Type Output<string>

The generated ID of the D1 database.

nodes

Type Object

The underlying resources this component creates.

nodes.database

Type D1Database

The Cloudflare D1 database.

SDK

Use the SDK in your runtime to interact with your infrastructure.


This is accessible through the Resource object in the SDK.

  • databaseId string

    The generated ID of the D1 database.

Bindings

When you link a D1 database, the database will be available to the worker and you can query it using its API methods.

index.ts
import { Resource } from "sst";
await Resource.MyDatabase.prepare(
"SELECT id FROM todo ORDER BY id DESC LIMIT 1",
).first();

Methods

static get

D1.get(name, databaseId, opts?)

Parameters

  • name string

    The name of the component.
  • databaseId string

    The database ID of the existing D1 Database.
  • opts? ComponentResourceOptions

Returns D1

Reference an existing D1 Database with the given database ID. This is useful when you create a D1 in one stage and want to share it in another. It avoids having to create a new D1 Database in the other stage.

Imagine you create a D1 Database in the dev stage. And in your personal stage giorgio, instead of creating a new database, you want to share the same database from dev.

sst.config.ts
const d1 = $app.stage === "giorgio"
? sst.cloudflare.D1.get("MyD1", "my-database-id")
: new sst.cloudflare.D1("MyD1");

Here my-database-id is the ID of the D1 Database created in the dev stage. You can find it by outputting the D1 Database in the dev stage.

sst.config.ts
return {
d1
};