Project Overview
CodeVault is a full-stack, multi-platform SaaS product that enables individuals, developers, and enterprises to generate, customize, manage, track, and verify every major code encoding standard — from QR codes and 1D barcodes to advanced 2D matrix formats. The platform is built with performance, scalability, and an exceptional user experience as first-class requirements.
The system is composed of four primary applications: a RESTful + WebSocket API (Node.js/TypeScript), a web portal (Next.js), a mobile app (React Native), and an enterprise back office (Next.js). All applications share a PostgreSQL database cluster and are orchestrated via a microservice-aligned monorepo.
- Performance first — sub-200ms API responses for code generation; sub-50ms for verification
- Developer-friendly — first-class API & SDK support with OpenAPI 3.1 documentation
- Enterprise-ready — SSO, RBAC, white-labelling, audit logs, SLA tiers
- Privacy by design — GDPR/CCPA compliant from day one
Target Audiences
Supported Use Cases
CodeVault supports an expansive range of encoding payloads and deployment scenarios across industries.
Code Type Support
| Category | Format | Max Data | Primary Use |
|---|---|---|---|
| 2D Matrix | QR Code (v1–v40) | 4,296 chars | URLs, payments, authentication |
| 2D Matrix | Data Matrix | 2,335 chars | Industrial, pharmaceutical labels |
| 2D Matrix | PDF417 | 1,850 bytes | ID documents, boarding passes, legal |
| 2D Matrix | Aztec Code | 3,067 chars | Transport tickets, boarding passes |
| 2D Matrix | MaxiCode | 93 chars | UPS/FedEx parcel tracking |
| 1D Linear | Code 128 / GS1-128 | — | Logistics, warehousing |
| 1D Linear | EAN-13 / EAN-8 | 13 digits | Retail product labelling |
| 1D Linear | UPC-A / UPC-E | 12 digits | North American retail |
| 1D Linear | Code 39 / Code 93 | — | Healthcare, military, automotive |
| 1D Linear | ITF / ITF-14 | — | Shipping cartons, GS1 packaging |
| 1D Linear | Codabar | — | Blood banks, libraries, FedEx |
| Postal | USPS IMb / PostNet | — | Mail sorting automation |
| Postal | Royal Mail 4-State | — | UK postal services |
| Emerging | DotCode | — | High-speed printing, tobacco marking |
| Emerging | HanXin Code | 7,827 chars | Chinese market, large payload |
Payload / Content Types
Core Feature Set
Code Generation Engine
- Static Codes — payload baked in; no redirect; ideal for print permanence
- Dynamic Codes — short-URL redirect layer; payload editable post-print without reprinting
- Bulk Generation — CSV/Excel upload with column mapping; generate thousands in one job with ZIP download
- Templated Generation — reusable templates for payload structure (e.g., product label schema)
- Scheduled Expiry — codes auto-deactivate on date/time, after N scans, or by geography
- Versioned Payloads — full history of payload changes for dynamic codes
Design & Customisation Studio
- Colour palette control — foreground, background, gradients, transparent backgrounds
- Custom logo / watermark embedding with configurable size and position
- Dot shape variants — square, rounded, circle, diamond, leaf, star
- Eye / finder pattern customisation (QR specific)
- Frame templates (call-to-action frames: "Scan Me", "Download App", custom text)
- Brand kit management — save org colours, fonts, and logo for team-wide consistency
- Error correction level selector (L / M / Q / H for QR)
- Export formats — PNG, SVG, PDF, EPS (vector), WebP
- Resolution & DPI control for print-ready exports (300dpi+)
Analytics & Tracking
- Scan Events — timestamp, IP (hashed for privacy), user-agent, referrer
- Geo Analytics — country, region, city-level heatmaps via MaxMind GeoIP2
- Device Breakdown — OS, browser, form factor (mobile/desktop/tablet)
- Time-series Charts — hourly / daily / weekly / monthly scan trends
- Funnel Analytics — scan → page visit → conversion tracking via UTM
- Campaign Aggregation — roll up analytics across multiple codes in a campaign
- Real-time Dashboard — live scan counter via WebSocket push
- Export Reports — CSV, PDF, Excel with scheduled email delivery
- Webhook Events — push scan events to external systems (Zapier, Slack, custom endpoints)
Verification & Authenticity
- Signed Codes — HMAC-SHA256 or Ed25519 digital signatures embedded in payload
- Verification API — instant signature validation endpoint (<50ms)
- Anti-counterfeit Tokens — unique one-time tokens per physical item
- Scan History — log of all verification events with timestamps and geo
- Tamper Detection — alerts when identical codes scanned in geographically implausible locations
- Certificate Chains — multi-level trust chains for B2B supply chain scenarios
Workspace & Collaboration
- Organisations → Teams → Projects → Folders → Codes hierarchy
- RBAC with granular permissions (Owner / Admin / Editor / Analyst / Viewer)
- Code sharing with external collaborators (link-based, time-limited)
- Activity feed and audit trail per workspace
- Comments and labels on individual codes
Developer Platform
- REST API with OpenAPI 3.1 specification + interactive Swagger UI
- GraphQL API for flexible queries (analytics, bulk operations)
- Official SDKs: JavaScript/TypeScript, Python, PHP, Go, Ruby, Java
- Webhook delivery with retry, signature verification, and event logs
- Sandbox / test mode environment with isolated data
- API Key management with scopes, IP allowlists, and rate limits per key
- OAuth 2.0 (Authorization Code + PKCE) for third-party integrations
System Architecture
Monorepo Structure
codevault/
├── apps/
│ ├── api/ # Node.js + TypeScript — Express/Fastify
│ ├── web/ # Next.js 15 — User portal
│ ├── admin/ # Next.js 15 — Back office
│ ├── mobile/ # React Native + Expo
│ └── dev-portal/ # Next.js 15 — Docs + Swagger
├── packages/
│ ├── core/ # Shared business logic, types, validators
│ ├── db/ # Drizzle ORM schema + migrations
│ ├── codegen/ # Code generation engine (pure TS)
│ ├── analytics/ # Analytics data models and queries
│ ├── ui/ # Shared design system components
│ └── config/ # ESLint, TypeScript, Prettier configs
├── infra/
│ ├── k8s/ # Kubernetes manifests
│ ├── terraform/ # IaC for AWS/GCP
│ └── docker/ # Dockerfiles per service
└── turbo.json # Turborepo pipeline config
Key Architectural Decisions
| Decision | Choice | Rationale |
|---|---|---|
| API Framework | Fastify | 3x faster than Express; schema-first validation with Zod; excellent TypeScript support |
| ORM | Drizzle ORM | Type-safe SQL; zero runtime overhead; excellent migration tooling; PostgreSQL native |
| Analytics Store | ClickHouse | Columnar store handles billions of scan events; sub-second aggregation queries |
| Queue System | BullMQ + Redis | Reliable job queues for bulk gen, webhook delivery, report emails |
| Short URLs | Edge Functions | Cloudflare Workers resolve redirects at edge (<5ms globally) without hitting origin |
| Caching Strategy | Redis + CDN | L1: Redis for hot code data; L2: Cloudflare for static assets and code images |
| Real-time | Socket.io | WebSocket push for live analytics dashboard and scan notifications |
| Search | Elasticsearch | Full-text search across codes, campaigns, audit logs; fuzzy matching for back office |
PostgreSQL Schema
Core entity relationships — all tables use UUID primary keys, soft deletes (deleted_at), and created_at / updated_at timestamps.
PostgreSQL Indexing Strategy
-- Hot path: dynamic code redirect resolution
CREATE INDEX idx_codes_short_id ON codes(short_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_codes_status ON codes(status, expires_at);
-- Analytics queries
CREATE INDEX idx_scan_events_code_scanned ON scan_events(code_id, scanned_at DESC);
CREATE INDEX idx_scan_events_country ON scan_events(country_code, scanned_at DESC);
-- Full-text & tag search
CREATE INDEX idx_codes_tags ON codes USING GIN(tags);
CREATE INDEX idx_codes_search ON codes USING GIN(
to_tsvector('english', name || ' ' || coalesce(description,''))
);
-- Partitioning for scan_events (by month)
CREATE TABLE scan_events PARTITION BY RANGE (scanned_at);
API Design
All API routes are prefixed with /api/v1. Authentication via Bearer {JWT} or X-API-Key: {key} header. Responses follow JSON:API-inspired structure.
Authentication
Code Management
Analytics
Verification
Short URL Redirect (Edge)
Node.js / TypeScript API
Technology Stack
| Layer | Technology | Purpose |
|---|---|---|
| Framework | Fastify 5 | HTTP server; plugin architecture; schema-validated routes |
| Language | TypeScript 5.5 | Strict mode; project references for monorepo |
| ORM | Drizzle ORM | Type-safe SQL; migrations; PostgreSQL dialects |
| Validation | Zod | Runtime schema validation; OpenAPI schema gen |
| Auth | Jose (JWT) | RS256 JWTs; PKCE OAuth; Passport.js strategies |
| Queue | BullMQ | Redis-backed; retries; priority; delayed jobs |
| Cache | ioredis | Redis client; cluster support; pipelines |
| Mailer | Resend + React Email | Transactional emails with typed templates |
| Storage | AWS S3 / R2 | Code images, document uploads, exports |
| Logging | Pino | Structured JSON logging; log levels; request ids |
| Testing | Vitest + Supertest | Unit + integration tests; Istanbul coverage |
Code Generation Engine
The @codevault/codegen package wraps best-in-class generation libraries into a unified, typed interface:
import { generateCode } from '@codevault/codegen';
const result = await generateCode({
type: 'qr',
payload: { type: 'url', value: 'https://example.com/product/123' },
design: {
foreground: '#1a1d27',
background: '#ffffff',
dotShape: 'rounded',
eyeShape: 'square',
logo: { url: 'https://cdn.../logo.png', size: 0.25 },
errorCorrection: 'H',
},
outputs: ['png', 'svg', 'pdf'],
dpi: 300,
signature: { sign: true, keyId: 'key_abc123' },
});
// result.images: { png: Buffer, svg: string, pdf: Buffer }
// result.signature: 'ed25519:abc...xyz'
// result.shortId: 'x7k2mQ'
Libraries Used Internally
- qrcode — QR code generation (v1–v40, all error correction levels)
- bwip-js — All 1D barcode formats + PDF417, DataMatrix, Aztec
- sharp — High-performance image processing; logo compositing; format conversion
- PDFKit — PDF output with vector QR embedding
- jsrsasign / @noble/ed25519 — Code signing and verification
Performance Targets
| Operation | P50 Target | P99 Target |
|---|---|---|
| Single code generation (PNG + SVG) | <120ms | <400ms |
| Dynamic code redirect (Cloudflare edge) | <5ms | <15ms |
| Verification API | <20ms | <50ms |
| Analytics query (7-day, single code) | <80ms | <200ms |
| Analytics query (30-day, campaign) | <300ms | <800ms |
| Bulk generation (1,000 codes) | <45s (async job) | <120s |
| List /codes (first page) | <40ms | <100ms |
Next.js Web Application
Technology Stack
- Next.js 15 (App Router, React 19, Server Components, Server Actions)
- TailwindCSS 4 with custom design system tokens
- shadcn/ui + custom component library (
@codevault/ui) - TanStack Query v5 — server state management, optimistic updates, infinite scroll
- Zustand — client state (design studio, UI state)
- React Hook Form + Zod — form validation (shared schemas with API)
- Recharts — analytics charts (line, bar, pie, geo choropleth)
- Framer Motion — animations, transitions, drag interactions
- i18next — internationalisation (en, fr, es, de, ja, zh, ar)
Key Pages & Modules
Rendering Strategy
| Page | Strategy | Reason |
|---|---|---|
| Landing / Marketing | SSG | Maximum speed, SEO, CDN-cached |
| Blog / Docs | ISR (60s) | Content updates without redeploy |
| Dashboard / Analytics | SSR + Client | Auth-gated, fresh data, CSR for real-time |
| Code Studio | CSR | Heavy canvas interactions; no SEO needed |
| Public verifier page | SSR | Dynamic result; sharable with OG metadata |
React Native Mobile App
Technology Stack
- React Native 0.76 with Expo SDK 52 (Managed → Bare workflow for camera access)
- Expo Router v4 — file-based routing, deep linking, universal links
- React Native Reanimated 3 — 60/120fps animations on UI thread
- React Native Vision Camera — high-performance camera with QR/barcode scanning frame processor
- MLKit Vision (iOS/Android) — on-device ML for ultra-fast code detection
- Expo SecureStore — biometric-protected token storage (keychain/keystore)
- TanStack Query — shared API layer (same hooks as web)
- MMKV — fast synchronous storage for cached data
- react-native-svg — render SVG code images natively
Core Mobile Features
Scanner Architecture
// Frame Processor runs on the camera thread (JSI, no bridge)
const frameProcessor = useFrameProcessor((frame) => {
'worklet';
const barcodes = scanBarcodes(frame, [
BarcodeFormat.QR_CODE,
BarcodeFormat.CODE_128,
BarcodeFormat.EAN_13,
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.PDF_417,
BarcodeFormat.AZTEC,
]);
if (barcodes.length > 0) {
runOnJS(onBarcodeDetected)(barcodes[0]);
}
}, []);
// Verification happens locally first (Ed25519),
// then syncs event to API async
Enterprise Back Office (Admin Portal)
A separate Next.js application deployed at admin.codevault.io, accessible only to CodeVault staff and designated enterprise administrators. Built with the same UI library but with a distinct layout and elevated permissions model.
Platform Admin Capabilities
Enterprise Features (per org)
- Custom domain — white-label redirect domain (e.g.,
qr.acme.com) - White-label portal — custom branding on web and mobile
- SAML 2.0 / OIDC SSO — Okta, Azure AD, Google Workspace, Ping Identity
- SCIM 2.0 provisioning — auto user/group sync from IdP
- Dedicated infrastructure — isolated DB schema or dedicated cluster option
- SLA tiers — 99.9% (Business), 99.95% (Enterprise), 99.99% (Enterprise+)
- Advanced RBAC — custom roles with granular permission matrices
- ERP/WMS integrations — SAP, Oracle, Microsoft Dynamics connectors
- Priority support — dedicated Slack channel, 4hr response SLA
- Compliance exports — SOC 2 reports, GDPR data portability, DPA agreements
Security Architecture
Authentication & Authorisation
- Passwords hashed with Argon2id (m=65536, t=3, p=4)
- JWTs signed with RS256; access token 15min TTL; refresh token 30d; stored in httpOnly cookies
- TOTP MFA via RFC 6238; backup codes (10x single-use, AES-256 encrypted)
- OAuth 2.0 with PKCE for Google, GitHub, Microsoft, Apple
- SAML 2.0 and OIDC for enterprise SSO
- Session revocation list in Redis (logout invalidates token family)
API Security
- Rate limiting per IP and per API key (sliding window algorithm in Redis)
- API keys scoped to specific operations (read-only, write, admin)
- Webhook payloads signed with HMAC-SHA256 (header:
X-CodeVault-Signature) - CORS with explicit allowlist; CSRF protection on stateful routes
- Request ID propagation for distributed tracing
- SQL injection protection via Drizzle ORM parameterised queries exclusively
- File upload scanning with ClamAV before S3 storage
Infrastructure Security
- All traffic TLS 1.3+ via Cloudflare
- Secrets managed via HashiCorp Vault or AWS Secrets Manager
- Database encryption at rest (AES-256); encrypted backups to separate AWS region
- VPC private networking; no public DB endpoints
- Kubernetes NetworkPolicies: zero-trust pod-to-pod communication
- Container image scanning (Trivy) in CI pipeline; no root containers
- WAF rules blocking OWASP Top 10 attack patterns
- DDoS protection via Cloudflare Magic Transit
Performance Engineering
Code Generation Optimisations
- Worker threads — image processing offloaded to Node.js worker thread pool (sharp is CPU-bound)
- Result caching — identical payload + design combinations cache-hit from Redis (TTL 1hr)
- Pre-generated assets — common sizes and formats generated eagerly and stored in S3
- Streaming responses — large export files stream to S3 without buffering in memory
Database Performance
- PgBouncer connection pooler (transaction mode) — 100x connection reuse
- Read replicas for all analytics and list queries (writes to primary only)
- Table partitioning on
scan_eventsby month — query pruning - Materialised views for pre-aggregated analytics (refreshed every 5 min)
- ClickHouse for high-cardinality analytics (billions of rows, sub-second aggregation)
- Autovacuum tuning; pg_partman for automatic partition management
Frontend Performance
- Next.js Partial Pre-rendering (PPR) for shell + streamed content
- React Server Components reduce client bundle by ~40%
- Code splitting per route + dynamic imports for heavy components (studio, analytics charts)
- Images served as WebP via Next.js Image with blur placeholders
- Bundle analysis in CI (bundlemon); budget alerts on regression
- Target: LCP <1.2s, FID <50ms, CLS <0.05 (Core Web Vitals)
Scalability Design
- Stateless API services — horizontal scaling via Kubernetes HPA
- Scan ingest via write-optimised queue (BullMQ) — decoupled from redirect latency
- ClickHouse cluster with 3+ shards — linear analytical throughput scaling
- Multi-region deployment with latency-based DNS routing (Route 53)
- Designed for 10M+ active codes and 1B+ scan events/year
Infrastructure & DevOps
Cloud Architecture
| Component | Service | Sizing (start) |
|---|---|---|
| Kubernetes Cluster | AWS EKS | 3x m7g.xlarge nodes, auto-scaling to 20 |
| PostgreSQL | AWS RDS Aurora PostgreSQL | db.r7g.large primary + 2 read replicas |
| Redis | AWS ElastiCache (Valkey) | cache.r7g.large, cluster mode |
| ClickHouse | ClickHouse Cloud / Self-hosted | 3-node cluster, 500GB NVMe |
| Object Storage | AWS S3 / Cloudflare R2 | Unlimited; R2 for zero-egress cost |
| CDN / Edge | Cloudflare | Enterprise plan; Workers for redirect |
| Search | Elastic Cloud | 2-node, hot-warm architecture |
| Secrets | AWS Secrets Manager | — |
| Resend + SES fallback | — |
CI/CD Pipeline
push → GitHub Actions:
├── lint (ESLint, Prettier, tsc --noEmit)
├── test (Vitest unit + integration, coverage ≥80%)
├── security scan (Trivy, npm audit, Semgrep)
├── build (Turborepo cache-aware parallel build)
├── docker build + push (ECR)
├── bundlemon (frontend budget check)
└── deploy:
├── staging (auto, on main branch)
└── production (manual approval gate)
Observability Stack
- Metrics — Prometheus scraping all services; Grafana dashboards (golden signals + custom)
- Tracing — OpenTelemetry → Grafana Tempo (distributed traces across all services)
- Logging — Pino JSON logs → Loki → Grafana (correlated with traces via trace ID)
- Alerting — PagerDuty integration; on-call rotation; runbook links in alerts
- Uptime — Better Uptime for external monitoring; status page at status.codevault.io
- Error Tracking — Sentry (API + Web + Mobile) with release tracking and performance profiling
Third-Party Integrations
Development Roadmap
Pricing Model
| Plan | Price | Codes | Scans/mo | Key Features |
|---|---|---|---|---|
| Free | $0 | 5 dynamic | 500 | QR only, basic design, 30-day analytics |
| Starter | $12/mo | 50 dynamic | 10,000 | All formats, full analytics, custom logo, 2 users |
| Pro | $39/mo | 500 dynamic | 100,000 | Bulk gen, campaigns, webhooks, API access, 10 users |
| Business | $149/mo | Unlimited | 1,000,000 | SSO, custom domain, white-label, 50 users, priority support |
| Enterprise | Custom | Unlimited | Unlimited | Dedicated infra, SLA, SCIM, ERP, dedicated support |