replit-sdk-patterns
Apply production-ready patterns for Replit Database, Object Storage, and Auth APIs. Use when implementing Replit integrations, structuring data access layers, or establishing team coding standards for Replit services. Trigger with phrases like "replit patterns", "replit best practices", "replit code patterns", "idiomatic replit", "replit SDK".
Best use case
replit-sdk-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Apply production-ready patterns for Replit Database, Object Storage, and Auth APIs. Use when implementing Replit integrations, structuring data access layers, or establishing team coding standards for Replit services. Trigger with phrases like "replit patterns", "replit best practices", "replit code patterns", "idiomatic replit", "replit SDK".
Teams using replit-sdk-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/replit-sdk-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How replit-sdk-patterns Compares
| Feature / Agent | replit-sdk-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Apply production-ready patterns for Replit Database, Object Storage, and Auth APIs. Use when implementing Replit integrations, structuring data access layers, or establishing team coding standards for Replit services. Trigger with phrases like "replit patterns", "replit best practices", "replit code patterns", "idiomatic replit", "replit SDK".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Replit SDK Patterns
## Overview
Production-ready patterns for Replit's built-in services: Key-Value Database (`@replit/database` / `replit.db`), Object Storage (`@replit/object-storage`), PostgreSQL (`DATABASE_URL`), and Auth headers. Covers singleton clients, error handling, and type-safe wrappers.
## Prerequisites
- `.replit` and `replit.nix` configured (see `replit-install-auth`)
- Familiarity with async/await patterns
- Understanding of Replit's service model
## Instructions
### Step 1: Database Client Singleton (Node.js)
```typescript
// src/db/kv.ts — Replit Key-Value Database wrapper
import Database from '@replit/database';
let instance: Database | null = null;
export function getKV(): Database {
if (!instance) {
instance = new Database();
}
return instance;
}
// Type-safe KV operations
export async function kvGet<T>(key: string): Promise<T | null> {
const value = await getKV().get(key);
return value as T | null;
}
export async function kvSet<T>(key: string, value: T): Promise<void> {
await getKV().set(key, value);
}
export async function kvList(prefix = ''): Promise<string[]> {
return getKV().list(prefix);
}
export async function kvDelete(key: string): Promise<void> {
await getKV().delete(key);
}
// Limits: 50 MiB total, 5,000 keys, 1 KB/key, 5 MiB/value
```
### Step 2: Object Storage Wrapper
```typescript
// src/storage/objects.ts — Replit App Storage (Object Storage)
import { Client } from '@replit/object-storage';
let storage: Client | null = null;
export function getStorage(): Client {
if (!storage) {
storage = new Client();
}
return storage;
}
// Upload with error handling
export async function uploadText(path: string, content: string): Promise<void> {
try {
await getStorage().uploadFromText(path, content);
} catch (err: any) {
if (err.name === 'BucketNotFoundError') {
throw new Error('Object Storage bucket not provisioned. Create one in the Object Storage pane.');
}
if (err.name === 'TooManyRequestsError') {
throw new Error('Object Storage rate limited. Retry after backoff.');
}
throw err;
}
}
// Download with fallback
export async function downloadText(path: string, fallback = ''): Promise<string> {
try {
const { value } = await getStorage().downloadAsText(path);
return value ?? fallback;
} catch {
return fallback;
}
}
// List with prefix filtering
export async function listObjects(prefix: string): Promise<string[]> {
const objects = await getStorage().list({ prefix });
return objects.map(obj => obj.name);
}
```
### Step 3: PostgreSQL Connection Pool
```typescript
// src/db/postgres.ts — Replit PostgreSQL
import { Pool, PoolConfig } from 'pg';
let pool: Pool | null = null;
export function getPool(): Pool {
if (!pool) {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL not set. Provision PostgreSQL in the Database pane.');
}
const config: PoolConfig = {
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
};
pool = new Pool(config);
pool.on('error', (err) => {
console.error('PostgreSQL pool error:', err.message);
});
}
return pool;
}
// Typed query helper
export async function query<T>(sql: string, params?: any[]): Promise<T[]> {
const result = await getPool().query(sql, params);
return result.rows as T[];
}
// Transaction helper
export async function withTransaction<T>(
fn: (client: import('pg').PoolClient) => Promise<T>
): Promise<T> {
const client = await getPool().connect();
try {
await client.query('BEGIN');
const result = await fn(client);
await client.query('COMMIT');
return result;
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
```
### Step 4: Auth Middleware Pattern
```typescript
// src/middleware/auth.ts — Replit Auth header extraction
import { Request, Response, NextFunction } from 'express';
export interface ReplitUser {
id: string;
name: string;
bio: string;
url: string;
profileImage: string;
roles: string;
teams: string;
}
export function extractUser(req: Request): ReplitUser | null {
const id = req.headers['x-replit-user-id'] as string;
if (!id) return null;
return {
id,
name: (req.headers['x-replit-user-name'] as string) || '',
bio: (req.headers['x-replit-user-bio'] as string) || '',
url: (req.headers['x-replit-user-url'] as string) || '',
profileImage: (req.headers['x-replit-user-profile-image'] as string) || '',
roles: (req.headers['x-replit-user-roles'] as string) || '',
teams: (req.headers['x-replit-user-teams'] as string) || '',
};
}
export function requireAuth(req: Request, res: Response, next: NextFunction) {
const user = extractUser(req);
if (!user) return res.status(401).json({ error: 'Login required' });
(req as any).user = user;
next();
}
```
### Step 5: Python Patterns
```python
# src/services/replit_services.py
from replit import db
from replit.object_storage import Client as ObjectStorage
import os, json
# KV Database — dict-like API
class KVStore:
@staticmethod
def get(key: str, default=None):
return db.get(key, default)
@staticmethod
def set(key: str, value):
db[key] = value
@staticmethod
def delete(key: str):
if key in db:
del db[key]
@staticmethod
def list_keys(prefix: str = '') -> list:
return db.prefix(prefix) if prefix else list(db.keys())
# Object Storage
class FileStore:
def __init__(self):
self._client = ObjectStorage()
def upload(self, path: str, content: str):
self._client.upload_from_text(path, content)
def download(self, path: str) -> str:
return self._client.download_as_text(path)
def exists(self, path: str) -> bool:
return self._client.exists(path)
def delete(self, path: str):
self._client.delete(path)
def list(self, prefix: str = '') -> list:
return [obj.name for obj in self._client.list(prefix=prefix)]
# Auth helper for Flask
def get_replit_user(request) -> dict | None:
user_id = request.headers.get('X-Replit-User-Id')
if not user_id:
return None
return {
'id': user_id,
'name': request.headers.get('X-Replit-User-Name', ''),
'roles': request.headers.get('X-Replit-User-Roles', ''),
'image': request.headers.get('X-Replit-User-Profile-Image', ''),
}
```
### Step 6: Retry with Backoff
```typescript
// src/utils/retry.ts
export async function withRetry<T>(
fn: () => Promise<T>,
opts = { maxRetries: 3, baseMs: 1000, maxMs: 30000 }
): Promise<T> {
for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
try {
return await fn();
} catch (err: any) {
if (attempt === opts.maxRetries) throw err;
const delay = Math.min(opts.baseMs * 2 ** attempt, opts.maxMs);
const jitter = Math.random() * delay * 0.1;
await new Promise(r => setTimeout(r, delay + jitter));
}
}
throw new Error('Unreachable');
}
```
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| Singleton client | All services | Avoids connection leaks |
| Typed wrappers | KV/SQL queries | Catches schema issues at compile time |
| Retry + backoff | Transient failures | Handles cold starts and rate limits |
| Transaction helper | Multi-step writes | Atomic operations, safe rollback |
## Resources
- [Replit Database](https://docs.replit.com/cloud-services/storage-and-databases/replit-database)
- [Object Storage TS SDK](https://docs.replit.com/cloud-services/storage-and-databases/object-storage/typescript-api-reference)
- [Object Storage Python SDK](https://docs.replit.com/reference/object-storage-python-sdk)
- [Replit Auth](https://docs.replit.com/replit-workspace/replit-auth)
## Next Steps
Apply patterns in `replit-core-workflow-a` for real-world usage.Related Skills
workhuman-sdk-patterns
Workhuman sdk patterns for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman sdk patterns".
wispr-sdk-patterns
Wispr Flow sdk patterns for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr sdk patterns".
windsurf-sdk-patterns
Apply production-ready Windsurf workspace configuration and Cascade interaction patterns. Use when configuring .windsurfrules, workspace rules, MCP servers, or establishing team coding standards for Windsurf AI. Trigger with phrases like "windsurf patterns", "windsurf best practices", "windsurf config patterns", "windsurfrules", "windsurf workspace".
windsurf-reliability-patterns
Implement reliable Cascade workflows with checkpoints, rollback, and incremental editing. Use when building fault-tolerant AI coding workflows, preventing Cascade from breaking builds, or establishing safe practices for multi-file AI edits. Trigger with phrases like "windsurf reliability", "cascade safety", "windsurf rollback", "cascade checkpoint", "safe cascade workflow".
webflow-sdk-patterns
Apply production-ready Webflow SDK patterns — singleton client, typed error handling, pagination helpers, and raw response access for the webflow-api package. Use when implementing Webflow integrations, refactoring SDK usage, or establishing team coding standards. Trigger with phrases like "webflow SDK patterns", "webflow best practices", "webflow code patterns", "idiomatic webflow", "webflow typescript".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
veeva-sdk-patterns
Veeva Vault sdk patterns for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva sdk patterns".
vastai-sdk-patterns
Apply production-ready Vast.ai SDK patterns for Python and REST API. Use when implementing Vast.ai integrations, refactoring SDK usage, or establishing coding standards for GPU cloud operations. Trigger with phrases like "vastai SDK patterns", "vastai best practices", "vastai code patterns", "idiomatic vastai".
twinmind-sdk-patterns
Apply production-ready TwinMind SDK patterns for TypeScript and Python. Use when implementing TwinMind integrations, refactoring API usage, or establishing team coding standards for meeting AI integration. Trigger with phrases like "twinmind SDK patterns", "twinmind best practices", "twinmind code patterns", "idiomatic twinmind".
together-sdk-patterns
Together AI sdk patterns for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together sdk patterns".
techsmith-sdk-patterns
TechSmith sdk patterns for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith sdk patterns".