Architectural Blueprint: Full-Stack Web Deployment & Production Operations
Deploying a modern full-stack web application to production requires orchestrating multiple infrastructure layers: version control, continuous integration and deployment pipelines, authoritative domain and DNS management, global CDN edge proxying with SSL encryption, managed database instances with connection pooling, secure session authentication, and payment gateway integration. This guide provides a complete, production-tested manual for taking an application from a local repository to a fully live, monetized platform.
1. Source Control Architecture & GitHub CI/CD Deployment
A solid production deployment starts with strict Git workflows and automated CI/CD pipelines. Never deploy untracked code directly to production servers.
- Branch Protection & Hygiene: Protect your
mainorproductionbranch by requiring pull request reviews and status checks to pass before merging. Ensure your.gitignoreexplicitly excludes.env,.env.local,node_modules/, and build artifacts. - Static Hosting vs Dynamic Server Execution: Static sites (Next.js static exports, Vite, Hugo) can be hosted at near-zero latency and cost on platforms like GitHub Pages, Cloudflare Pages, or Vercel Edge. Dynamic full-stack applications requiring server-side API routes, Node.js runtimes, or database pooling must be deployed to containerized environments such as Render.com, Railway.app, or serverless functions on Vercel / AWS Lambda.
- Automated GitHub Actions Workflow: Create
.github/workflows/deploy.ymlto run linters, type checks, build steps, and automated deployments upon every push tomain.
2. Custom Domain Registration & TLD Architecture (.com vs .co.ke)
Your domain is your primary digital identity. Understanding the differences between generic Top-Level Domains (gTLDs) and Country Code Top-Level Domains (ccTLDs) is essential for DNS routing and brand trust.
- Global TLDs (.com, .org, .net): Governed by ICANN and managed by registries like Verisign. Purchased through global accredited registrars (e.g., Namecheap, Cloudflare Registrar, Porkbun, GoDaddy). Global TLDs offer instant provisioning, DNSSEC support, and global brand recognition.
- Kenyan ccTLDs (.co.ke, .ke, .or.ke): Governed by the Kenya Network Information Centre (KeNIC). Purchased through accredited Kenyan registrars (such as Sasahost, Truehost, EACdirectory, Kenya Web Experts). Ideal for local SEO ranking in Kenya, building domestic consumer trust, and complying with national regulatory standards.
- Core DNS Record Types:
A Record:Maps a hostname directly to an IPv4 address (e.g.,192.0.2.1).AAAA Record:Maps a hostname to an IPv6 address.CNAME Record:Canonical Name record that aliases one hostname to another (e.g., pointingfixit.cybertechcomps.comtocybertech-harry.github.io).TXT Record:Stores text information used for domain ownership validation (Google Search Console, GitHub domain verification), SPF, and DKIM email records.
3. Cloudflare DNS Configuration, Edge Proxying & SSL/TLS
Cloudflare acts as a reverse proxy, DDoS shield, and global Content Delivery Network (CDN). Routing your domain through Cloudflare ensures fast asset caching and bulletproof HTTPS encryption.
- Nameserver Delegation: Log in to your domain registrar (e.g., KeNIC registrar or Namecheap) and replace the default nameservers with Cloudflare assigned authoritative nameservers (e.g.,
ada.ns.cloudflare.comandburt.ns.cloudflare.com). - DNS Record Provisioning & CNAME Flattening: In the Cloudflare DNS dashboard, add your target records. For static sites hosted on GitHub Pages or Vercel, create a CNAME record with Orange Cloud proxying enabled. Cloudflare automatically flattens CNAME records at the root apex domain (
@), eliminating RFC-1034 apex limitations. - SSL/TLS Encryption Mode: Set SSL/TLS mode to Full (Strict). This guarantees end-to-end encryption between the user's browser, Cloudflare's edge data centers, and your origin server with a valid origin certificate, preventing man-in-the-middle exploits.
- Edge Security Rules: Enable Always Use HTTPS, Automatic HTTPS Rewrites, HTTP/2 or HTTP/3 (QUIC), and configure Cloudflare WAF (Web Application Firewall) to filter bot attacks and brute-force traffic.
4. Modern Cloud Database Integrations (Supabase, Firebase, Railway, Render)
Selecting and connecting the appropriate database tier depends on your data model (relational vs document NoSQL), scaling profile, and query complexity:
- Supabase (Managed PostgreSQL & Row Level Security):
Provides a full relational PostgreSQL engine with built-in real-time subscriptions, storage, and pgvector for AI applications.
Use Prisma, Drizzle, or the native
@supabase/supabase-jsclient. For serverless applications (Next.js Edge or Vercel), use connection pooling via PgBouncer on port6543(e.g.,postgresql://postgres:[PASSWORD]@db.[PROJECT-REF].supabase.co:6543/postgres?pgbouncer=true) to prevent exhausting Postgres connection limits. Enable Row Level Security (RLS) policies so clients can query safely without custom backend middleware. - Firebase Firestore (Serverless NoSQL Document Store):
Optimized for real-time collaborative applications, mobile apps, and rapid event streaming.
Use the client SDK (
firebase/firestore) for direct frontend queries protected by Firestore Security Rules (allow read, write: if request.auth != null;). For server-side privileged mutations or background cron tasks, initialize the Firebase Admin SDK using a secure Service Account JSON key stored in environment variables. - Railway.app (Containerized DBs & Microservices):
Provides instant automated deployment of PostgreSQL, MySQL, Redis, and MongoDB containers with persistent volumes.
Offers private service networking (e.g., connecting a backend directly to
postgres.railway.internal:5432without exposing the database to the public internet) and public TCP proxies for external development. Environment variables likeDATABASE_URLare injected automatically into dependent services. - Render.com (Managed PostgreSQL & Web Services):
Provides fully managed PostgreSQL with automated daily backups, read replicas, and SSL enforcement.
Web services running on Render connect via internal database URLs (zero bandwidth cost, lower latency), while external connections require appending
?sslmode=requireto prevent unencrypted transmissions across public networks.
5. User Authentication Systems & Session Architecture
Authentication establishes user identity, while authorization enforces permissions. Never build custom password hashing algorithms from scratch in production.
- NextAuth.js / Auth.js: The gold standard for Next.js applications. Supports OAuth providers (Google, GitHub, Apple) and Credentials login. Configure sessions to use encrypted JWTs stored in HTTP-only, Secure, SameSite=Lax cookies. This eliminates Cross-Site Scripting (XSS) attack vectors that compromise tokens stored in browser
localStorage. - Firebase Authentication: Turnkey multi-factor authentication supporting OAuth, email magic links, and SMS OTP. When using Firebase Auth with a custom backend, pass the client-side ID token via the
Authorization: Bearer [TOKEN]header and verify it on the server usingadmin.auth().verifyIdToken(idToken). - Route Protection with Middleware: Use edge middleware (e.g.,
middleware.tsin Next.js) to intercept unauthorized requests before pages or API routes render, immediately redirecting unauthenticated users to/login.
6. Payment Gateway Integration: Safaricom Daraja 3.0 & PayHero Kenya API
Monetizing applications in Kenya and East Africa requires seamless integration with mobile money ecosystems (M-Pesa). Below is the complete implementation architecture for both direct telco integration and aggregator channels.
A. Safaricom Daraja 3.0 M-Pesa API Architecture
Safaricom Daraja 3.0 provides direct REST APIs for Lipa Na M-Pesa Online (STK Push), Customer-to-Business (C2B), and Business-to-Customer (B2C) disbursements.
- Obtain Credentials: Register an account on the Safaricom Developer Portal, create an App, and generate your
Consumer Key,Consumer Secret,Passkey, andBusinessShortCode(Paybill or Till Number). - OAuth Token Generation: Issue an HTTP GET request to
https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentialswith HTTP Basic Authentication usingBase64(ConsumerKey:ConsumerSecret). The API returns anaccess_tokenvalid for 3599 seconds. - Construct STK Push (Lipa Na M-Pesa Online):
Generate a timestamp formatted as
YYYYMMDDHHmmss(e.g.,20260913073000). Create the security password by computingBase64(BusinessShortCode + Passkey + Timestamp).Send a POST request to
/mpesa/stkpush/v1/processrequestwith the following payload:{ "BusinessShortCode": "174379", "Password": "MTc0Mzc5YmZiMjc5Zjlh...", "Timestamp": "20260913073000", "TransactionType": "CustomerPayBillOnline", "Amount": 100, "PartyA": "254712345678", "PartyB": "174379", "PhoneNumber": "254712345678", "CallBackURL": "https://api.cybertechcomps.com/api/v1/mpesa/callback", "AccountReference": "INVOICE-8921", "TransactionDesc": "Web Hosting Plan Payment" } - Handling the Webhook Callback:
Safaricom dispatches an asynchronous HTTPS POST request to your designated
CallBackURL. Check ifBody.stkCallback.ResultCode === 0. If 0, parse theCallbackMetadata.Itemarray to extractMpesaReceiptNumber,Amount,TransactionDate, andPhoneNumber. Save this record to your database and update the user's order status immediately.
B. PayHero Kenya API Integration
PayHero Kenya serves as a modern payment aggregator offering unified APIs for M-Pesa STK Push, Paybill, Buy Goods Till, and bank payouts without requiring custom telco VPNs or complex reconciliation infrastructure.
- Channel Authentication: Configure a channel in the PayHero dashboard to obtain your
API Key,API Secret, andChannel ID. - Initiate Payment Request: Make an authorized POST request to PayHero's payment endpoint:
// POST https://backend.payhero.co.ke/api/v2/payments { "amount": 500, "phone_number": "0712345678", "channel_id": 842, "provider": "m-pesa", "external_reference": "ORDER-5412", "callback_url": "https://api.cybertechcomps.com/api/v1/payhero/webhook" } - Webhook IPN Validation: Handle incoming Instant Payment Notifications (IPN). Always verify the callback HMAC signature or query the PayHero status verification endpoint before fulfilling orders to prevent forged webhook attacks.
7. Production Security Checklist & Credential Isolation
- Zero Secrets in Git: Never store
ConsumerSecret,Passkey, database passwords, or JWT secrets in client code or Git. Use environment secrets managers (GitHub Actions Secrets, Render Environment Groups, Railway Variables). - Public Webhook HTTPS Requirement: Both Safaricom Daraja and PayHero require valid public HTTPS callback URLs. For local testing, use tunneling tools like
cloudflared tunnelorngrokto expose your local port safely. - Replay Attack Prevention: Track processed M-Pesa receipt numbers in an indexed database table with a
UNIQUEconstraint. If duplicate callback payloads arrive, respond with HTTP 200 without re-crediting the user account.