by @encoredev
Declare databases, Pub/Sub, cron jobs, and secrets with Encore.ts.
Encore.ts uses declarative infrastructure - you define resources in code and Encore handles provisioning:
encore run) - Encore runs infrastructure in Docker (Postgres, Redis, etc.)All infrastructure must be declared at package level (top of file), not inside functions.
import { SQLDatabase } from "encore.dev/storage/sqldb";
// CORRECT: Package level
const db = new SQLDatabase("mydb", {
migrations: "./migrations",
});
// WRONG: Inside function
async function setup() {
const db = new SQLDatabase("mydb", { migrations: "./migrations" });
}
Create migrations in the migrations/ directory:
service/
├── encore.service.ts
├── api.ts
├── db.ts
└── migrations/
├── 001_create_users.up.sql
└── 002_add_email_index.up.sql
Migration naming: {number}_{description}.up.sql
import { Topic } from "encore.dev/pubsub";
interface OrderCreatedEvent {
orderId: string;
userId: string;
total: number;
}
// Package level declaration
export const orderCreated = new Topic<OrderCreatedEvent>("order-created", {
deliveryGuarantee: "at-least-once",
});
await orderCreated.publish({
orderId: "123",
userId: "user-456",
total: 99.99,
});
import { Subscription } from "encore.dev/pubsub";
const _ = new Subscription(orderCreated, "send-confirmation-email", {
handler: async (event) => {
await sendEmail(event.userId, event.orderId);
},
});
import { CronJob } from "encore.dev/cron";
import { api } from "encore.dev/api";
// The endpoint to call
export const cleanupExpiredSessions = api(
{ expose: false },
async (): Prom...