replit-reference-architecture

1
1
Source

Implement Replit reference architecture with best-practice project layout. Use when designing new Replit integrations, reviewing project structure, or establishing architecture standards for Replit applications. Trigger with phrases like "replit architecture", "replit best practices", "replit project structure", "how to organize replit", "replit layout".

Install

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

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

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.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

11240

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

9033

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

18828

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5519

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,6851,428

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,2671,333

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,5381,147

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,356809

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,264728

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,489684