RE

replit-reference-architecture

Defines production-grade project layouts and architectural standards for Replit-hosted applications.

Install

mkdir -p .claude/skills/replit-reference-architecture && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5452" && unzip -o skill.zip -d .claude/skills/replit-reference-architecture && rm skill.zip

Installs to .claude/skills/replit-reference-architecture

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement Replit reference architecture with best-practice project layout,
74 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Standardize project folder structure
  • Configure centralized environment validation
  • Implement singleton service patterns
  • Define deployment-ready configuration files
  • Set up global error handling middleware

How it works

It establishes a structured directory layout and configuration pattern that separates business logic, data services, and middleware to ensure production readiness on Replit.

Inputs & outputs

You give it
Project requirements and architecture standards
You get back
Standardized project layout and configuration

When to use replit-reference-architecture

  • Designing new Replit application architecture
  • Refactoring existing projects for better structure
  • Standardizing team development patterns
  • Defining production-ready project layouts

About this skill

Replit Reference Architecture

Overview

Production architecture for applications on Replit. Covers project structure, configuration files, data layer (PostgreSQL + KV + Object Storage), authentication, deployment strategy, and the platform constraints that shape architectural decisions.

Architecture Diagram

                    ┌──────────────────────────┐
                    │    Client (Browser)       │
                    └──────────┬───────────────┘
                               │ HTTPS
                    ┌──────────▼───────────────┐
                    │  Replit Proxy (TLS, Auth) │
                    │  Injects X-Replit-User-*  │
                    └──────────┬───────────────┘
                               │
┌──────────────────────────────▼──────────────────────────────┐
│                 Replit Deployment                            │
│                                                              │
│  ┌─────────────┐  ┌──────────────┐  ┌───────────────────┐  │
│  │ .replit      │  │ replit.nix   │  │ Secrets (AES-256) │  │
│  │ (run/build)  │  │ (Nix deps)   │  │ (env vars)        │  │
│  └─────────────┘  └──────────────┘  └───────────────────┘  │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐   │
│  │              Express / Flask Server                   │   │
│  │  Routes │ Auth Middleware │ Error Handler │ Health    │   │
│  └────────┬───────────────────────────────────┬─────────┘   │
│           │                                   │              │
│  ┌────────▼──────────┐  ┌───────────────────▼────────────┐ │
│  │  PostgreSQL       │  │  Replit KV Database            │ │
│  │  (DATABASE_URL)   │  │  (REPLIT_DB_URL)               │ │
│  │  Dev + Prod DBs   │  │  50 MiB, 5K keys              │ │
│  └───────────────────┘  └────────────────────────────────┘ │
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐│
│  │  Object Storage (App Storage)                           ││
│  │  File uploads, backups, large data                      ││
│  │  @replit/object-storage SDK                             ││
│  └─────────────────────────────────────────────────────────┘│
│                                                              │
│  Deployment: Autoscale │ Reserved VM │ Static               │
└──────────────────────────────────────────────────────────────┘

Instructions

Step 1: Project Structure

my-replit-app/
├── .replit                    # Run + deployment configuration
├── replit.nix                 # System-level Nix dependencies
├── package.json               # npm dependencies + scripts
├── tsconfig.json              # TypeScript config
├── src/
│   ├── index.ts               # Entry point — Express setup
│   ├── config.ts              # Secrets validation + env config
│   ├── routes/
│   │   ├── api.ts             # Business logic endpoints
│   │   ├── auth.ts            # Auth-related routes
│   │   └── health.ts          # Health check (required for deploy)
│   ├── services/
│   │   ├── postgres.ts        # PostgreSQL pool singleton
│   │   ├── kv.ts              # Replit KV Database wrapper
│   │   └── storage.ts         # Object Storage wrapper
│   ├── middleware/
│   │   ├── auth.ts            # Replit Auth header extraction
│   │   ├── rateLimit.ts       # Rate limiting
│   │   └── errors.ts          # Global error handler
│   └── types/
│       └── index.ts           # Shared type definitions
├── tests/
│   ├── api.test.ts            # API integration tests
│   └── services.test.ts       # Service unit tests
└── scripts/
    └── migrate.ts             # Database migration scripts

Step 2: Configuration Files

# .replit
entrypoint = "src/index.ts"
run = "npx tsx src/index.ts"

modules = ["nodejs-20:v8-20230920-bd784b9"]

[nix]
channel = "stable-24_05"

[env]
NODE_ENV = "development"

[deployment]
run = ["sh", "-c", "npx tsx src/index.ts"]
build = ["sh", "-c", "npm ci --production"]
deploymentTarget = "autoscale"

[unitTest]
language = "nodejs"

[languages.typescript]
pattern = "**/*.ts"
# replit.nix
{ pkgs }: {
  deps = [
    pkgs.nodejs-20_x
    pkgs.nodePackages.typescript-language-server
  ];
}

Step 3: Configuration Module

// src/config.ts — centralized configuration with validation
export const config = {
  port: parseInt(process.env.PORT || '3000'),
  nodeEnv: process.env.NODE_ENV || 'development',
  isProduction: process.env.NODE_ENV === 'production',
  repl: {
    slug: process.env.REPL_SLUG || 'unknown',
    owner: process.env.REPL_OWNER || 'unknown',
    id: process.env.REPL_ID,
  },
  db: {
    url: process.env.DATABASE_URL,
    kvUrl: process.env.REPLIT_DB_URL,
  },
} as const;

// Validate required secrets at import time
const REQUIRED_SECRETS = ['DATABASE_URL'];
const missing = REQUIRED_SECRETS.filter(k => !process.env[k]);
if (missing.length > 0 && config.isProduction) {
  console.error(`FATAL: Missing secrets: ${missing.join(', ')}`);
  process.exit(1);
}

Step 4: Data Layer Strategy

StorageUse WhenLimits
PostgreSQLStructured data, relations, queriesPlan-dependent
Replit KVSimple cache, session data, counters50 MiB, 5K keys
Object StorageFiles, images, backups, large blobsPlan-dependent
// src/services/postgres.ts
import { Pool } from 'pg';
import { config } from '../config';

export const pool = new Pool({
  connectionString: config.db.url,
  ssl: { rejectUnauthorized: false },
  max: 5,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 5000,
});

// src/services/kv.ts
import Database from '@replit/database';
export const kv = new Database();

// src/services/storage.ts
import { Client } from '@replit/object-storage';
export const storage = new Client();

Step 5: Entry Point Pattern

// src/index.ts
import express from 'express';
import { config } from './config';
import { pool } from './services/postgres';
import healthRouter from './routes/health';
import apiRouter from './routes/api';
import { requireAuth } from './middleware/auth';
import { errorHandler } from './middleware/errors';

const app = express();
app.use(express.json({ limit: '1mb' }));

// Public routes
app.use(healthRouter);

// Protected routes
app.use('/api', requireAuth, apiRouter);

// Global error handler (must be last)
app.use(errorHandler);

// Start server — bind to 0.0.0.0 (required for Replit)
app.listen(config.port, '0.0.0.0', () => {
  console.log(`[${config.repl.slug}] Running on port ${config.port}`);
  // Pre-connect database
  pool.query('SELECT 1').catch(err => {
    console.error('Database connection failed:', err.message);
  });
});

// Graceful shutdown
process.on('SIGTERM', async () => {
  console.log('SIGTERM received, shutting down...');
  await pool.end();
  process.exit(0);
});

Platform Constraints

ConstraintImpactMitigation
Ephemeral filesystemFiles lost on restartUse DB or Object Storage
Cold starts (Autoscale)5-30s first requestReserved VM or lazy loading
Memory limitsOOM killsStream data, limit pool size
Public ReplsSource visibleNever hardcode secrets
Container restartsState lossExternal state (DB/Storage)

Error Handling

IssueCauseSolution
Cold start slowHeavy imports at startupLazy-load non-critical modules
DB connection refusedPostgreSQL not provisionedCreate database in Database pane
Secrets undefinedNot in Secrets tabAdd via sidebar lock icon
Filesystem writes lostEphemeral containerUse Object Storage or PostgreSQL

Resources

Next Steps

For deployment, see replit-deploy-integration. For multi-environment, see replit-multi-env-setup.

When not to use it

  • When building simple, single-file scripts

Prerequisites

Replit Deployment access

Limitations

  • Ephemeral filesystem causes file loss on restart
  • Cold starts impact performance on Autoscale deployments

How it compares

It provides a specific, platform-aware architecture that accounts for Replit's ephemeral filesystem and container lifecycle, unlike generic project templates.

Compared to similar skills

replit-reference-architecture side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
replit-reference-architecture (this skill)125dReviewIntermediate
software-architecture3336moNo flagsIntermediate
architect-review1094moNo flagsAdvanced
mcp-builder1363moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

software-architecture

davila7

Guide for quality focused software architecture. This skill should be used when users want to write code, design architecture, analyze code, in any case that relates to software development.

333868

architect-review

sickn33

Master software architect specializing in modern architecture patterns, clean architecture, microservices, event-driven systems, and DDD. Reviews system designs and code changes for architectural integrity, scalability, and maintainability. Use PROACTIVELY for architectural decisions.

109320

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

solid-principles

SmidigStorm

Enforce SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) in object-oriented design. Use when writing or reviewing classes and modules.

57236

codex

Lucklyric

Invoke Codex CLI for complex coding tasks requiring high reasoning capabilities. This skill should be invoked when users explicitly mention "Codex", request complex implementation challenges, advanced reasoning, or need high-reasoning model assistance. Automatically triggers on codex-related requests and supports session continuation for iterative development.

32238

architecture-patterns

wshobson

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.

55214

Search skills

Search the agent skills registry