
Tinybird Typescript Sdk Guidelines
- 724 installs
- 20 repo stars
- Updated July 29, 2026
- tinybirdco/tinybird-agent-skills
tinybird-typescript-sdk-guidelines is an agent skill that teaches type-safe use of the @tinybirdco/sdk package so developers who build Tinybird analytics backends can define datasources, pipes, endpoints, and clients wit
About
tinybird-typescript-sdk-guidelines is a Tinybird-authored agent skill for the official @tinybirdco/sdk TypeScript package. It guides agents through installing and configuring the SDK, defining datasources and pipes in TypeScript with complete type inference, creating typed Tinybird clients, and running type-safe ingestion and queries. The skill also covers tinybird dev, build, and deploy commands for TypeScript-based Tinybird projects and supports migration from legacy Tinybird workflows. Developers reach for tinybird-typescript-sdk-guidelines when scaffolding new Tinybird backends in TypeScript, debugging type errors in pipe definitions, or ensuring ingestion and query code matches datasource schemas without runtime surprises.
- 11 focused rule files covering every aspect from getting started to advanced materialized views
- Full type inference patterns for datasources, pipes, and typed clients
- Clear CLI command guidance for dev, build, deploy, and preview workflows
- Migration instructions from legacy .datasource/.pipe files to TypeScript definitions
- Connection patterns for Kafka, S3, GCS plus copy and sink pipes
Tinybird Typescript Sdk Guidelines by the numbers
- 724 all-time installs (skills.sh)
- +24 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #398 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/tinybirdco/tinybird-agent-skills --skill tinybird-typescript-sdk-guidelinesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 724 |
|---|---|
| repo stars | ★ 20 |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 29, 2026 |
| Repository | tinybirdco/tinybird-agent-skills ↗ |
How do you define Tinybird pipes with TypeScript SDK?
Get complete type-safe guidance when defining Tinybird datasources, pipes, endpoints and clients using the official TypeScript SDK.
Who is it for?
Backend developers building Tinybird analytics pipelines in TypeScript who need type-safe datasource, pipe, and client definitions via @tinybirdco/sdk.
Skip if: Teams using only Tinybird's CLI with .datasource and .pipe files without the TypeScript SDK, or projects not using Tinybird at all.
When should I use this skill?
User works with @tinybirdco/sdk, defines Tinybird datasources or pipes in TypeScript, or runs tinybird dev/build/deploy on a TS project.
What you get
Typed datasource definitions, pipe configurations, Tinybird client code, and deployable TypeScript Tinybird project files.
- Typed datasource and pipe definitions
- Type-safe Tinybird client code
Files
Tinybird TypeScript SDK Guidelines
Guidance for using the @tinybirdco/sdk package to define Tinybird resources in TypeScript with complete type inference.
When to Apply
- Installing or configuring @tinybirdco/sdk
- Defining datasources or pipes in TypeScript
- Creating typed Tinybird clients
- Using type-safe ingestion or queries
- Running tinybird dev/build/deploy commands for TypeScript projects
- Migrating from legacy .datasource/.pipe files to TypeScript
- Defining connections (Kafka, S3, GCS)
- Creating materialized views, copy pipes, or sink pipes
Rule Files
rules/getting-started.mdrules/configuration.mdrules/defining-datasources.mdrules/defining-endpoints.mdrules/typed-client.mdrules/low-level-api.mdrules/cli-commands.mdrules/connections.mdrules/materialized-views.mdrules/copy-sink-pipes.mdrules/tokens.md
Quick Reference
- Install:
npm install @tinybirdco/sdk - Initialize:
npx tinybird init - Dev mode:
tinybird dev(uses configureddevMode, typically branch) - Build:
tinybird build(builds against configured dev target) - Deploy:
tinybird deploy(deploys to main/production) - Preview in CI:
tinybird preview - Server-side only; never expose tokens in browsers
SDK CLI Commands
The SDK includes CLI commands for development, preview, and deployment workflows.
CLI 4.0 Build/Deploy Model
- Configure your default development target once in
tinybird.config.*(devMode). - Run
tinybird buildwithout environment flags for normal workflows. - Run
tinybird deployto publish to Tinybird Cloud main. - Use
--local/--branchonly as explicit overrides.
tinybird init
Initialize a new TypeScript Tinybird project:
npx tinybird init
npx tinybird init --force # Overwrite existing files
npx tinybird init --skip-login # Skip browser authenticationDetects existing .datasource and .pipe files for incremental migration.
tinybird migrate
Migrate legacy datafiles to TypeScript definitions:
tinybird migrate "tinybird/**/*.datasource" "tinybird/**/*.pipe" "tinybird/**/*.connection"
tinybird migrate tinybird/legacy --out ./tinybird.migration.ts
tinybird migrate tinybird --dry-runConverts .datasource, .pipe, and .connection files into a TypeScript definitions file.
tinybird dev
Watch schema files and auto-sync to Tinybird:
tinybird dev # Watch and sync using configured devMode
tinybird dev --local # Sync with local container
tinybird dev --branch # Force branch mode for this runImportant: In branch mode, feature branches are expected; main/master are blocked to prevent accidental production changes.
tinybird build
Build and validate resources using your configured development target:
tinybird build # Build to devMode target (branch or local)
tinybird build --dry-run # Preview build operations
tinybird build --local # Build to local container
tinybird build --branch # Build to branch for this runUse tinybird build for iterative development; it does not publish to production.
tinybird deploy
Deploy resources to the main workspace (production):
tinybird deploy # Deploy to main/production
tinybird deploy --dry-run # Preview without deploying
tinybird deploy --check # Validate without applying changes
tinybird deploy --wait # Wait for deployment completion
tinybird deploy --allow-destructive-operations # Allow breaking changesThis is the only way to deploy to main.
tinybird preview
Create or refresh a CI preview environment for the current branch:
tinybird previewUse this in pull request workflows so preview apps query isolated Tinybird preview branches.
tinybird pull
Download cloud resources as native datafiles:
tinybird pull # Pull to default location
tinybird pull --output-dir ./tinybird-datafiles
tinybird pull --force # Overwrite existing filestinybird login
Authenticate via browser:
tinybird loginUseful for existing projects or token refresh.
tinybird branch
Manage branches:
tinybird branch list # List all branches
tinybird branch status # Show current branch status
tinybird branch delete <name> # Delete a branchtinybird info
Display workspace, local, and project configuration:
tinybird info # Show configuration
tinybird info --json # Output as JSONDevelopment Workflow
1. npx tinybird init - Initialize project 2. Define datasources and pipes in TypeScript 3. tinybird build or tinybird dev - Iterate against configured dev target 4. tinybird preview in CI - Create preview branch environment per PR 5. tinybird deploy - Deploy to production after merge
Important Notes
- The CLI auto-generates datafiles from TypeScript definitions before
build,deploy, andpreview - Use
--check/--dry-runbefore production deploys when in doubt - The SDK CLI is separate from the
tbCLI but complementary
SDK Configuration
Configuration File
Create a configuration file in your project root. Supported formats (in priority order):
1. tinybird.config.mjs - ESM with dynamic logic 2. tinybird.config.cjs - CommonJS with dynamic logic 3. tinybird.config.json - Standard JSON (default) 4. tinybird.json - Legacy format
Configuration Options
{
"include": [
"src/tinybird/datasources.ts",
"src/tinybird/pipes.ts",
"src/tinybird/legacy.datasource",
"src/tinybird/legacy.pipe"
],
"token": "${TINYBIRD_TOKEN}",
"baseUrl": "https://api.tinybird.co",
"devMode": "branch"
}Configuration Fields
include: Array of file paths to include (TypeScript files and legacy.datasource/.pipefiles)token: API token, supports environment variable interpolation with${VAR_NAME}baseUrl: Tinybird API base URLdevMode: Development mode (branchfor cloud branches,localfor local container)
Mixed Formats
You can combine TypeScript files with legacy .datasource and .pipe files for gradual migration:
{
"include": [
"src/tinybird/datasources.ts",
"src/tinybird/pipes.ts",
"legacy/events.datasource",
"legacy/analytics.pipe"
]
}Path Alias Configuration
Add to tsconfig.json for cleaner imports:
{
"compilerOptions": {
"paths": {
"@tinybird/client": ["./src/tinybird/client.ts"]
}
}
}Defining Connections
Connections define external data sources that Tinybird can integrate with.
Kafka Connection
import { defineKafkaConnection, secret } from "@tinybirdco/sdk";
export const eventsKafka = defineKafkaConnection("events_kafka", {
bootstrapServers: "kafka.example.com:9092",
securityProtocol: "SASL_SSL",
saslMechanism: "PLAIN",
key: secret("KAFKA_KEY"),
secret: secret("KAFKA_SECRET"),
});S3 Connection
import { defineS3Connection } from "@tinybirdco/sdk";
export const landingS3 = defineS3Connection("landing_s3", {
region: "us-east-1",
arn: "arn:aws:iam::123456789012:role/tinybird-s3-access",
});GCS Connection
import { defineGCSConnection, secret } from "@tinybirdco/sdk";
export const landingGCS = defineGCSConnection("landing_gcs", {
serviceAccountCredentialsJson: secret("GCS_SERVICE_ACCOUNT_CREDENTIALS_JSON"),
});Using Secrets
The secret() function references secrets stored in Tinybird:
import { secret } from "@tinybirdco/sdk";
// Reference a secret by name
const apiKey = secret("MY_API_KEY");Secrets must be created in Tinybird before deploying connections that use them.
Using Connections in Datasources
import { defineDatasource, t, engine } from "@tinybirdco/sdk";
import { eventsKafka, landingS3, landingGCS } from "./connections";
// Kafka datasource
export const kafkaEvents = defineDatasource("kafka_events", {
schema: {
timestamp: t.dateTime(),
payload: t.string(),
},
engine: engine.mergeTree({ sortingKey: ["timestamp"] }),
kafka: {
connection: eventsKafka,
topic: "events",
groupId: "events-consumer",
autoOffsetReset: "earliest",
},
});
// S3 datasource
export const s3Landing = defineDatasource("s3_landing", {
schema: {
timestamp: t.dateTime(),
session_id: t.string(),
},
engine: engine.mergeTree({ sortingKey: ["timestamp"] }),
s3: {
connection: landingS3,
bucketUri: "s3://my-bucket/events/*.csv",
schedule: "@auto",
},
});
// GCS datasource
export const gcsLanding = defineDatasource("gcs_landing", {
schema: {
timestamp: t.dateTime(),
session_id: t.string(),
},
engine: engine.mergeTree({ sortingKey: ["timestamp"] }),
gcs: {
connection: landingGCS,
bucketUri: "gs://my-gcs-bucket/events/*.csv",
schedule: "@auto",
},
});Copy Pipes and Sink Pipes
Copy Pipes
Copy pipes execute SQL and write results to a datasource on a schedule or on-demand.
Scheduled Copy Pipe
import { defineCopyPipe, node } from "@tinybirdco/sdk";
export const dailySnapshot = defineCopyPipe("daily_snapshot", {
description: "Daily snapshot of statistics",
datasource: snapshotDatasource, // Target datasource
schedule: "0 0 * * *", // Cron: daily at midnight
mode: "append",
nodes: [
node({
name: "snapshot",
sql: `
SELECT today() AS snapshot_date, pathname, count() AS views
FROM page_views
WHERE toDate(timestamp) = today() - 1
GROUP BY pathname
`,
}),
],
});On-Demand Copy Pipe
export const manualReport = defineCopyPipe("manual_report", {
description: "On-demand report generation",
datasource: reportDatasource,
schedule: "@on-demand",
mode: "replace",
nodes: [
node({
name: "report",
sql: `SELECT * FROM events WHERE timestamp >= now() - interval 7 day`,
}),
],
});Copy Modes
| Mode | Description |
|---|---|
append | Add rows to existing data (default) |
replace | Replace all data in target datasource |
Schedule Options
| Schedule | Description |
|---|---|
"0 0 * * *" | Cron expression (daily at midnight) |
"*/5 * * * *" | Every 5 minutes |
"@on-demand" | Manual trigger only |
"@once" | Run once on deployment |
Sink Pipes
Sink pipes publish query results to external systems (Kafka, S3).
Kafka Sink
import { defineSinkPipe, node } from "@tinybirdco/sdk";
import { eventsKafka } from "./connections";
export const kafkaEventsSink = defineSinkPipe("kafka_events_sink", {
sink: {
connection: eventsKafka,
topic: "events_export",
schedule: "@on-demand",
},
nodes: [
node({
name: "publish",
sql: `SELECT timestamp, payload FROM kafka_events`,
}),
],
});S3 Sink
import { defineSinkPipe, node } from "@tinybirdco/sdk";
import { landingS3 } from "./connections";
export const s3EventsSink = defineSinkPipe("s3_events_sink", {
sink: {
connection: landingS3,
bucketUri: "s3://my-bucket/exports/",
fileTemplate: "events_{date}",
format: "csv",
schedule: "@once",
strategy: "create_new",
compression: "gzip",
},
nodes: [
node({
name: "export",
sql: `SELECT timestamp, session_id FROM s3_landing`,
}),
],
});S3 Sink Options
| Option | Description |
|---|---|
bucketUri | S3 bucket and path prefix |
fileTemplate | Filename template (supports {date}, {time}) |
format | Output format: csv, json, parquet |
schedule | Cron expression or @on-demand, @once |
strategy | create_new or overwrite |
compression | none, gzip, lz4 |
Defining Datasources
Basic Datasource Definition
import { defineDatasource, t, engine, type InferRow } from "@tinybirdco/sdk";
export const pageViews = defineDatasource("page_views", {
description: "Page view tracking data",
schema: {
timestamp: t.dateTime(),
pathname: t.string(),
session_id: t.string(),
country: t.string().lowCardinality().nullable(),
},
engine: engine.mergeTree({
sortingKey: ["pathname", "timestamp"],
}),
});
export type PageViewsRow = InferRow<typeof pageViews>;Schema Types
The t object provides type definitions:
t.string()- String typet.int32(),t.int64(),t.uint32(),t.uint64()- Integer typest.float32(),t.float64()- Float typest.dateTime()- DateTime typet.date()- Date typet.boolean()- Boolean type (stored as UInt8)
Type Modifiers
Chain modifiers on types:
.nullable()- Make column nullable.lowCardinality()- Use LowCardinality encoding for low-unique strings.array()- Array of the type
Example:
schema: {
tags: t.string().array(),
country: t.string().lowCardinality().nullable(),
score: t.float64().nullable(),
}Engine Configuration
engine: engine.mergeTree({
sortingKey: ["column1", "column2"],
partitionKey: "toYYYYMM(timestamp)", // optional
})For aggregating materialized views:
engine: engine.aggregatingMergeTree({
sortingKey: ["date", "dimension"],
})Type Inference
Use InferRow to extract the TypeScript type from a datasource:
export type PageViewsRow = InferRow<typeof pageViews>;
// Results in: { timestamp: Date; pathname: string; session_id: string; country: string | null }Defining Endpoints (Pipes)
Basic Endpoint Definition
import {
defineEndpoint, node, t, p,
type InferParams,
type InferOutputRow
} from "@tinybirdco/sdk";
export const topPages = defineEndpoint("top_pages", {
description: "Get the most visited pages",
params: {
start_date: p.dateTime(),
end_date: p.dateTime(),
limit: p.int32().optional(10),
},
nodes: [
node({
name: "aggregated",
sql: `
SELECT pathname, count() AS views
FROM page_views
WHERE timestamp >= {{DateTime(start_date)}}
AND timestamp <= {{DateTime(end_date)}}
GROUP BY pathname
ORDER BY views DESC
LIMIT {{Int32(limit, 10)}}
`,
}),
],
output: {
pathname: t.string(),
views: t.uint64(),
},
});
export type TopPagesParams = InferParams<typeof topPages>;
export type TopPagesOutput = InferOutputRow<typeof topPages>;Parameter Types
The p object provides parameter definitions:
p.string()- String parameterp.int32(),p.int64()- Integer parametersp.float32(),p.float64()- Float parametersp.dateTime()- DateTime parameterp.date()- Date parameter
Parameter Modifiers
.optional(defaultValue)- Make parameter optional with a default value
Example:
params: {
limit: p.int32().optional(10),
filter: p.string().optional(""),
}Multi-Node Pipes
Define multiple nodes for complex transformations:
nodes: [
node({
name: "filtered",
sql: `
SELECT * FROM events
WHERE timestamp >= {{DateTime(start_date)}}
`,
}),
node({
name: "aggregated",
sql: `
SELECT date, count() as total
FROM filtered
GROUP BY date
`,
}),
],SQL Templating
Use Tinybird templating in SQL:
{{Type(param_name)}}- Parameter with type{{Type(param_name, default)}}- Parameter with default value
WHERE user_id = {{String(user_id)}}
AND date >= {{Date(start_date, '2024-01-01')}}
LIMIT {{Int32(limit, 100)}}Type Inference
export type TopPagesParams = InferParams<typeof topPages>;
// Results in: { start_date: Date; end_date: Date; limit?: number }
export type TopPagesOutput = InferOutputRow<typeof topPages>;
// Results in: { pathname: string; views: bigint }Tinybird TypeScript SDK Overview
What is it
The @tinybirdco/sdk is a TypeScript package that enables developers to define Tinybird resources with complete type inference. You can author datasources, pipes, and queries in TypeScript, then synchronize them directly to Tinybird.
Requirements
- TypeScript: Version 4.9 or higher
- Node.js: 20 LTS or later (non-EOL versions officially supported)
- Server-side only; web browsers are not supported to protect API credentials
Installation
npm install @tinybirdco/sdkProject Initialization
npx tinybird init
npx tinybird init --force # Overwrite existing files
npx tinybird init --skip-login # Skip browser authenticationThis generates:
tinybird.config.json- Configuration filesrc/tinybird/datasources.ts- Data source definitionssrc/tinybird/pipes.ts- Pipe/endpoint definitionssrc/tinybird/client.ts- Typed client
Environment Setup
Create .env.local:
TINYBIRD_TOKEN=p.your_token_hereKey Features
- Full type inference with autocomplete for datasources and pipes
- Type-safe data ingestion catching schema mismatches at development time
- Typed query results based on endpoint definitions
- Mixed formats: combine TypeScript with legacy
.datasource/.pipefiles - Branch safety: dev mode blocks deployment to main branch
Public Tinybird API (Low-Level)
For cases requiring a decoupled API wrapper without the typed client:
Creating the API Client
import { createTinybirdApi } from "@tinybirdco/sdk";
const api = createTinybirdApi({
baseUrl: "https://api.tinybird.co",
token: process.env.TINYBIRD_TOKEN!,
});Querying Endpoints
interface TopPagesRow { pathname: string; visits: number }
interface TopPagesParams { start_date: string; end_date: string; limit?: number }
const topPages = await api.query<TopPagesRow, TopPagesParams>("top_pages", {
start_date: "2024-01-01",
end_date: "2024-01-31",
limit: 5,
});
// topPages.data is typed as TopPagesRow[]Ingesting Data
interface EventRow { timestamp: Date; event_name: string; pathname: string }
await api.ingest<EventRow>("events", {
timestamp: new Date(),
event_name: "page_view",
pathname: "/home",
});
// Batch ingestion
await api.ingest<EventRow>("events", [
{ timestamp: new Date(), event_name: "page_view", pathname: "/home" },
{ timestamp: new Date(), event_name: "click", pathname: "/home" },
]);Executing Raw SQL
interface CountResult { total: number }
const sqlResult = await api.sql<CountResult>(
"SELECT count() AS total FROM events"
);
// sqlResult.data[0].totalPer-Request Token Override
await api.request("/v1/workspace", {
token: process.env.TINYBIRD_BRANCH_TOKEN,
});When to Use Low-Level API
- Existing projects not using TypeScript definitions
- Dynamic endpoint names or parameters
- Direct SQL execution needs
- Gradual migration from other HTTP clients
Materialized Views
Materialized views automatically aggregate data as it arrives, enabling real-time analytics.
Basic Materialized View
A materialized view consists of: 1. A target datasource with aggregate columns 2. A materialized view definition that populates it
import { defineDatasource, defineMaterializedView, t, engine, node } from "@tinybirdco/sdk";
// Target datasource with aggregate columns
export const dailyStats = defineDatasource("daily_stats", {
description: "Daily aggregated statistics",
schema: {
date: t.date(),
pathname: t.string(),
views: t.simpleAggregateFunction("sum", t.uint64()),
unique_sessions: t.aggregateFunction("uniq", t.string()),
},
engine: engine.aggregatingMergeTree({
sortingKey: ["date", "pathname"],
}),
});
// Materialized view that populates it
export const dailyStatsMv = defineMaterializedView("daily_stats_mv", {
description: "Materialize daily page view aggregations",
datasource: dailyStats,
nodes: [
node({
name: "aggregate",
sql: `
SELECT
toDate(timestamp) AS date,
pathname,
count() AS views,
uniqState(session_id) AS unique_sessions
FROM page_views
GROUP BY date, pathname
`,
}),
],
});Aggregate Types
SimpleAggregateFunction
For simple aggregations (sum, min, max, any):
views: t.simpleAggregateFunction("sum", t.uint64()),
minValue: t.simpleAggregateFunction("min", t.float64()),
maxValue: t.simpleAggregateFunction("max", t.float64()),AggregateFunction
For complex aggregations (uniq, quantile, etc.):
uniqueUsers: t.aggregateFunction("uniq", t.string()),
p95Latency: t.aggregateFunction("quantile(0.95)", t.float64()),SQL State Functions
In materialized view SQL, use state functions to prepare aggregates:
| Final Function | State Function |
|---|---|
count() | count() (no state needed for SimpleAggregateFunction) |
sum(col) | sum(col) (no state needed) |
uniq(col) | uniqState(col) |
quantile(0.95)(col) | quantileState(0.95)(col) |
avg(col) | avgState(col) |
Querying Materialized Views
When querying, use merge functions for AggregateFunction columns:
const endpoint = defineEndpoint("daily_stats_query", {
nodes: [
node({
name: "query",
sql: `
SELECT
date,
pathname,
sum(views) AS total_views,
uniqMerge(unique_sessions) AS unique_sessions
FROM daily_stats
GROUP BY date, pathname
`,
}),
],
output: {
date: t.date(),
pathname: t.string(),
total_views: t.uint64(),
unique_sessions: t.uint64(),
},
});Engine Selection
Always use aggregatingMergeTree for materialized view targets:
engine.aggregatingMergeTree({
sortingKey: ["date", "dimension1", "dimension2"],
});Tokens
Static Tokens
Define named tokens and attach them to datasources and endpoints:
import { defineToken, defineDatasource, defineEndpoint, t, node } from "@tinybirdco/sdk";
// Define tokens
const appToken = defineToken("app_read");
const ingestToken = defineToken("ingest_token");
// Attach to datasource
export const events = defineDatasource("events", {
schema: {
timestamp: t.dateTime(),
event_name: t.string(),
},
tokens: [
{ token: appToken, scope: "READ" },
{ token: ingestToken, scope: "APPEND" },
],
});
// Attach to endpoint
export const topEvents = defineEndpoint("top_events", {
nodes: [node({ name: "endpoint", sql: "SELECT * FROM events LIMIT 10" })],
output: { timestamp: t.dateTime(), event_name: t.string() },
tokens: [{ token: appToken, scope: "READ" }],
});Token Scopes
| Resource | Available Scopes |
|---|---|
| Datasources | READ, APPEND |
| Pipes/Endpoints | READ |
JWT Token Creation
Create short-lived JWT tokens for secure scoped access. Useful for:
- Frontend applications calling Tinybird APIs directly
- Multi-tenant applications with row-level security
- Time-limited access with automatic expiration
import { createClient } from "@tinybirdco/sdk";
const client = createClient({
baseUrl: "https://api.tinybird.co",
token: process.env.TINYBIRD_ADMIN_TOKEN!, // Requires ADMIN scope
});
const { token } = await client.tokens.createJWT({
name: "user_123_session",
expiresAt: new Date(Date.now() + 60 * 60 * 1000), // 1 hour
scopes: [
{
type: "PIPES:READ",
resource: "user_dashboard",
fixed_params: { user_id: 123 },
},
],
limits: { rps: 10 },
});
// Use the JWT for client-side queries
const userClient = createClient({
baseUrl: "https://api.tinybird.co",
token, // The JWT
});JWT Scope Types
| Scope | Description |
|---|---|
PIPES:READ | Read access to a specific pipe endpoint |
DATASOURCES:READ | Read access to a datasource |
DATASOURCES:APPEND | Append access to a datasource |
JWT Scope Options
| Option | Description |
|---|---|
resource | Name of the pipe or datasource |
fixed_params | Parameters embedded in token (cannot be overridden) |
filter | SQL WHERE clause for datasource filtering |
Example: Multi-Tenant Access
const orgToken = await client.tokens.createJWT({
name: "org_acme_access",
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 1 day
scopes: [
{
type: "DATASOURCES:READ",
resource: "events",
filter: "org_id = 'acme'",
},
{
type: "PIPES:READ",
resource: "analytics_dashboard",
fixed_params: { org_id: "acme" },
},
],
limits: { rps: 100 },
});JWT Limits
| Option | Description |
|---|---|
rps | Requests per second limit |
Creating the Typed Client
Client Setup
// src/tinybird/client.ts
import { createTinybirdClient } from "@tinybirdco/sdk";
import { pageViews, type PageViewsRow } from "./datasources";
import { topPages, type TopPagesParams, type TopPagesOutput } from "./pipes";
export const tinybird = createTinybirdClient({
datasources: { pageViews },
pipes: { topPages },
});
export type { PageViewsRow, TopPagesParams, TopPagesOutput };
export { pageViews, topPages };Using the Typed Client
Type-Safe Ingestion
import { tinybird, type PageViewsRow } from "@tinybird/client";
// Autocomplete and type checking for all fields
await tinybird.ingest.pageViews({
timestamp: new Date(),
pathname: "/home",
session_id: "abc123",
country: "US",
});
// Batch ingestion
await tinybird.ingest.pageViews([
{ timestamp: new Date(), pathname: "/home", session_id: "abc", country: "US" },
{ timestamp: new Date(), pathname: "/about", session_id: "abc", country: "US" },
]);Type-Safe Queries
import { tinybird } from "@tinybird/client";
// Autocomplete for parameters, typed results
const result = await tinybird.query.topPages({
start_date: new Date("2024-01-01"),
end_date: new Date(),
limit: 5,
});
// result.data is fully typed: { pathname: string, views: bigint }[]
for (const row of result.data) {
console.log(`${row.pathname}: ${row.views} views`);
}Client Benefits
- Autocomplete: Full IDE support for datasource fields and endpoint parameters
- Type Safety: Catch schema mismatches at compile time
- Refactoring: Rename fields and parameters with confidence
- Documentation: Types serve as inline documentation
Related skills
How it compares
Pick tinybird-typescript-sdk-guidelines over generic database skills when the project uses @tinybirdco/sdk and needs type-safe pipe and datasource definitions in TypeScript.
FAQ
Which package does tinybird-typescript-sdk-guidelines cover?
tinybird-typescript-sdk-guidelines covers the official @tinybirdco/sdk npm package for defining Tinybird datasources, pipes, endpoints, and clients in TypeScript with complete type inference for ingestion and queries.
Does tinybird-typescript-sdk-guidelines support Tinybird CLI commands?
tinybird-typescript-sdk-guidelines includes guidance for running tinybird dev, build, and deploy commands on TypeScript-based Tinybird projects, alongside SDK configuration and typed resource definitions.
Is Tinybird Typescript Sdk Guidelines safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.