Implement Replit PII handling, data retention, and GDPR/CCPA compliance patterns.
Use when handling sensitive data, implementing data redaction, configuring retention policies,
or ensuring compliance with privacy regulations for Replit integrations.
Trigger with phrases like "replit data", "replit PII",
"replit GDPR", "replit data retention", "replit privacy", "replit CCPA".
Manage application data securely across Replit's three storage systems: PostgreSQL (relational), Key-Value Database (simple cache/state), and Object Storage (files/blobs). Covers connection patterns, security, data validation, and choosing the right storage for each use case.
Prerequisites
Replit account with Workspace access
PostgreSQL provisioned in Database pane (for SQL use cases)
Understanding of Replit Secrets for credentials
Storage Decision Matrix
Need
Storage
API
Limits
Structured data, queries
PostgreSQL
pg npm / psycopg2
Plan-dependent
Simple key-value, cache
Replit KV Database
@replit/database / replit.db
50 MiB, 5K keys
Files, images, backups
Object Storage
@replit/object-storage
Plan-dependent
Instructions
Step 1: PostgreSQL — Secure Connection
// src/services/database.ts
import { Pool, PoolConfig } from 'pg';
function createPool(): Pool {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL not set. Create a database in the Database pane.');
}
const config: PoolConfig = {
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }, // Required for Replit PostgreSQL
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
};
const pool = new Pool(config);
// Log errors without exposing connection string
pool.on('error', (err) => {
console.error('Database pool error:', err.message);
// Never: console.error(err) — may contain credentials
});
return pool;
}
export const pool = createPool();
// Parameterized queries ONLY — never string concatenation
export async function findUser(userId: string) {
// GOOD: parameterized
const result = await pool.query(
'SELECT id, username, created_at FROM users WHERE id = $1',
[userId]
);
return result.rows[0];
// BAD: SQL injection risk
// pool.query(`SELECT * FROM users WHERE id = '${userId}'`)
}
Dev vs Production databases:
Replit auto-provisions separate databases:
- Development: used when running in Workspace ("Run" button)
- Production: used when accessed via deployment URL
View in Database pane:
- Development tab: test data, iterate freely
- Production tab: live customer data, handle with care
Both use the same DATABASE_URL — Replit routes automatically.
Step 2: Key-Value Database — Session & Cache
Node.js:
// src/services/cache.ts
import Database from '@replit/database';
const db = new Database();
// Cache with TTL using KV
export async function cacheGet<T>(key: string): Promise<T | null> {
const entry = await db.get(key) as { value: T; expiresAt: number } | null;
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
await db.delete(key);
return null;
}
return entry.value;
}
export async function cacheSet<T>(key: string, value: T, ttlMs: number): Promise<void> {
await db.set(key, { value, expiresAt: Date.now() + ttlMs });
}
// Session storage
export async function setSession(sessionId: string, data: any): Promise<void> {
await db.set(`session:${sessionId}`, {
...data,
createdAt: Date.now(),
});
}
export async function getSession(sessionId: string): Promise<any> {
return db.get(`session:${sessionId}`);
}
// Clean up expired sessions
export async function cleanSessions(): Promise<number> {
const keys = await db.list('session:');
let cleaned = 0;
const oneDay = 24 * 60 * 60 * 1000;
for (const key of keys) {
const session = await db.get(key) as any;
if (session && Date.now() - session.createdAt > oneDay) {
await db.delete(key);
cleaned++;
}
}
return cleaned;
}
// Limits reminder: 50 MiB total, 5,000 keys, 1 KB/key, 5 MiB/value
Python:
from replit import db
import json, time
# Dict-like API
db["settings"] = {"theme": "dark", "lang": "en"}
settings = db["settings"]
# List keys by prefix
user_keys = db.prefix("user:")
# Delete
del db["old_key"]
# Cache pattern with TTL
def cache_set(key: str, value, ttl_seconds: int):
db[f"cache:{key}"] = {
"value": value,
"expires_at": time.time() + ttl_seconds
}
def cache_get(key: str):
entry = db.get(f"cache:{key}")
if not entry or time.time() > entry["expires_at"]:
return None
return entry["value"]