When the user wants to import historical Stripe data. Also use when the user mentions "backfill stripe data," "syncBackfill," "import stripe data," "sync existing data," or "historical sync."
You are an expert in backfilling historical Stripe data using stripe-sync-engine. Your goal is to help users import their existing Stripe data into PostgreSQL.
Before proceeding, verify:
Create scripts/backfill-stripe.ts:
import { StripeSync } from "stripe-sync-engine";
const stripeSync = new StripeSync({
poolConfig: {
connectionString: process.env.DATABASE_URL!,
max: 10,
},
stripeSecretKey: process.env.STRIPE_SECRET_KEY!,
stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
schema: "stripe",
autoExpandLists: true,
backfillRelatedEntities: true,
});
async function main() {
const startDateArg = process.argv[2];
if (!startDateArg) {
console.error("Usage: npm run stripe:backfill <start-date-unix-timestamp>");
console.error("Example: npm run stripe:backfill 1704067200");
process.exit(1);
}
const timestamp = parseInt(startDateArg, 10);
console.log(`Backfilling Stripe data from ${new Date(timestamp * 1000).toISOString()}...`);
await stripeSync.syncBackfill({
object: "all",
created: { gte: timestamp },
});
console.log("Backfill completed successfully");
}
main().catch((error) => {
console.error("Backfill failed:", error);
process.exit(1);
});
Add to package.json:
{
"scripts": {
"stripe:backfill": "tsx scripts/backfill-stripe.ts"
}
}
Run:
# Backfill from January 1, 2024 (Unix timestamp)
npm run stripe:backfill 1704067200
# Get Unix timestamp for a date (macOS/Linux)
date -d "2024-01-01" +%s
Create app/api/sync/backfill/route.ts:
import { NextResponse } from "next/server";
import { stripeSync } from "@/lib/stripeSync";
export async function POST(request: Request) {
const { object = "all", startDate } = await request.json();
try {
const result = await stripeSync.syncBackfill({
object,
created: startDate ? { gte: startDate } : undefined,
});
return NextResponse.json({ status: "completed", result });
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return NextResponse.json({ error: message }, { status: 500 });
}
}
The object parameter accepts:
| Value | Description |
|---|---|
all | All supported object types |
customer | Customer records |
product | Product catalog |
price | Price objects |
plan | Legacy plan objects |
subscription | Subscription records |
invoice | Invoice records |
charge | Charge records |
payment_intent | Payment intents |
payment_method | Payment methods |
setup_intent | Setup intents |
dispute | Dispute records |
The created parameter supports Stripe's RangeQueryParam:
// All objects created after a date