PERFORMANCE & SEO · PUBLISHED · 2026-12-03

Engineering a Bilingual EN/AR Portfolio on Cloudflare Workers with Zero TBT & Agentic Discovery

Replacing WebGL overhead with idle-deferred 2D canvas, inlining CSS, responsive WebP srcSet, strict CSP, llms.txt, and ARD.

Cloudflare Workers · Vite · Pre-rendered Markdown · llms.txt · ARD · Cloudflare D1

Live

A software engineer's portfolio is itself a production system. Treating sanad.id.ly as an engineering artifact meant holding it to the same architectural standards as client platforms: fast initial paint without main-thread contention, bilingual English/Arabic (LTR/RTL) support, zero-cookie edge APIs, strict security headers, and first-class discoverability for both search crawlers and AI agents.

This post documents the concrete technical decisions implemented in this repository—every one verifiable directly in vite.config.ts, PixiSmoke.tsx, Hero.tsx, worker/index.ts, wrangler.jsonc, and public/_headers.

1. Edge Architecture: Cloudflare Workers + D1 + Selective Asset Bypass

The site runs on Cloudflare Workers (wrangler.jsonc) with a static dist/ asset bundle (binding: "ASSETS", not_found_handling: "single-page-application") paired with a Cloudflare D1 database (portfolio-db) for inquiries and engineering-notes subscribers.

Rather than routing every image and hashed JavaScript chunk through Worker compute, wrangler.jsonc configures run_worker_first selectively:

{
  "name": "portfolio",
  "main": "worker/index.ts",
  "compatibility_date": "2026-12-02",
  "assets": {
    "directory": "./dist",
    "binding": "ASSETS",
    "not_found_handling": "single-page-application",
    "run_worker_first": [
      "/*",
      "!/assets/*",
      "!/images/*",
      "!/favicon.svg",
      "!/og.webp"
    ]
  }
}

With negative exclusions (!/assets/*, !/images/*, !/favicon.svg, !/og.webp), static media and immutable bundles serve straight from the edge cache, while HTML routes and /api/* endpoints enter worker/index.ts. Inside the Worker:

  • Requests to www.sanad.id.ly receive a canonical 301 redirect to https://sanad.id.ly.
  • POST /api/* routes enforce origin validation (isAllowedOrigin), honeypot filtering (body.website), and server-side Cloudflare Turnstile verification (https://challenges.cloudflare.com/turnstile/v0/siteverify using CF-Connecting-IP).
  • Validated submissions persist via parameterized D1 statements (env.DB.prepare(...).bind(...).run()) while Telegram alerts dispatch non-blockingly with ctx.waitUntil(...).

2. Eliminating Main-Thread Blocking: Idle-Deferred 24fps 2D Canvas Smoke

Ambient hero animations often degrade Total Blocking Time (TBT) when a WebGL renderer initializes synchronously on mount and ticks at 60fps. In Hero.tsx, the atmospheric smoke layer (PixiSmoke) is code-split via React.lazy inside <Suspense fallback={null}> so it never blocks first paint.

Inside src/components/portfolio/PixiSmoke.tsx, the implementation avoids heavy WebGL shaders in favor of a lightweight 2D Canvas pipeline:

  • Pre-rendered offscreen sprites: At startup, createSmokePuff generates three 128x128 radial-gradient puff canvases once instead of computing gradients per frame.
  • Idle-deferred initialization: Startup waits for window.requestIdleCallback(start, { timeout: 1200 }) (with a 180ms setTimeout fallback) so hydration and critical user interactions finish first.
  • 24fps frame pacing: FRAME_INTERVAL_MS = 42 caps rendering of the 18 wisps (WISP_COUNT = 18) to roughly 24fps, keeping per-frame main-thread execution sub-millisecond.
  • Visibility & accessibility awareness: An IntersectionObserver (threshold: 0.05) and document.hidden check pause animation whenever the hero leaves the viewport or tab focus. When (prefers-reduced-motion: reduce) matches, it renders a single static frame and exits without scheduling requestAnimationFrame.
const FRAME_INTERVAL_MS = 42; // ~24 fps keeps main-thread frame time sub-millisecond
const WISP_COUNT = 18;

const loop = (now: number) => {
  if (destroyed) return;
  rafId = window.requestAnimationFrame(loop);

  if (!visible || document.hidden) {
    lastTime = now;
    return;
  }

  const deltaMs = now - lastTime;
  if (deltaMs < FRAME_INTERVAL_MS) return;
  lastTime = now - (deltaMs % FRAME_INTERVAL_MS);

  const dtScale = Math.min(deltaMs / 16.67, 4);
  elapsed += 0.015 * dtScale;
  drawFrame(dtScale, elapsed);
};

3. Zero Render-Blocking CSS via a Post-Build Vite Plugin

Even a small external stylesheet forces an extra network round-trip before First Contentful Paint. In vite.config.ts, a custom post-build plugin (inlineBuiltCssPlugin) intercepts the generated bundle in generateBundle, reads every .css asset, replaces its <link> tag in index.html with an inline <style> block, and removes the standalone .css file from the output:

function inlineBuiltCssPlugin(): Plugin {
  return {
    name: "inline-built-css",
    apply: "build",
    enforce: "post",
    generateBundle(_options, bundle) {
      const htmlAsset = bundle["index.html"];
      if (!htmlAsset || htmlAsset.type !== "asset" || typeof htmlAsset.source !== "string") {
        return;
      }

      let html = htmlAsset.source;
      for (const [fileName, chunk] of Object.entries(bundle)) {
        if (!fileName.endsWith(".css") || chunk.type !== "asset") continue;
        const cssText = typeof chunk.source === "string"
          ? chunk.source
          : Buffer.from(chunk.source).toString("utf8");
        const linkRegex = new RegExp(
          `<link[^>]+href=["']/${fileName.replace(/[.*+?^${}()|[\]\\]/g, "\\

Sanad AlArousi (سند العروسي) | Software Engineer

Engineering systems that endure. Full-stack web, Flutter mobile, backend architecture, CI/CD pipelines, formal SDLC (PMBOK, SWEBOK, ISO/IEC/IEEE 29148), and open-source developer tools.

سند العروسي — مهندس برمجيات متخصص في الأنظمة المتكاملة وتطبيقات الموبايل والأتمتة وفق المعايير الهندسية.

Portfolio Sections & Documentation

Core Stack: TypeScript, React, Flutter, Python, Django REST, ERPNext, PostgreSQL, Docker, Cloudflare Workers. Notable Systems: LibreOffice-MCP, Overcast Cloud Platform, Masayef (Ministry of Youth), Export119.

Contact: me@sanad.id.ly

amp;")}["'][^>]*>\\s*`, "i" ); if (linkRegex.test(html)) { html = html.replace(linkRegex, `<style>${cssText}</style>\n`); delete bundle[fileName]; } } htmlAsset.source = html; }, }; }

Meanwhile, Google Fonts (Inter, IBM Plex Sans Arabic, JetBrains Mono, and Cormorant Garamond) load non-blockingly using media="print" on the <link id="gfonts"> element with a <noscript> fallback, ensuring typography enhancement never delays initial render.

4. Responsive WebP srcSet, Explicit Dimensions & Bilingual SEO

The hero portrait is the Largest Contentful Paint (LCP) candidate on desktop and mobile. Both index.html (<link rel="preload" as="image" ...>) and Hero.tsx declare identical responsive WebP candidates and viewport sizes:

  • srcSet: /images/hero-640.webp 640w, /images/hero-768.webp 768w, /images/hero-960.webp 960w, /images/hero.webp 1200w
  • sizes: (max-width: 767px) 100vw, (max-width: 1023px) 68vw, 56vw
  • Intrinsic dimensions width={1200} and height={1600} reserve layout space to avoid Cumulative Layout Shift (CLS), paired with fetchPriority="high" and decoding="async".

For bilingual SEO and pre-rendered Markdown content (marked + highlight.js authoring .en.md and .ar.md pairs), index.html exposes hreflang="en" (/en), hreflang="ar" (/ar), hreflang="x-default" (/), OpenGraph/Twitter metadata pointing to /og.webp, and structured schema.org/Person JSON-LD.

5. Strict CSP, Immutable Caching & Agentic Discovery (llms.txt + ARD)

Security and cache policies are codified declaratively in public/_headers. Every response ships with X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Cross-Origin-Opener-Policy: same-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), Strict-Transport-Security, and a strict Content-Security-Policy locking down default-src 'self', object-src 'none', frame-ancestors 'none', and base-uri 'self'. Hashed /assets/*, /images/*, and /og.webp carry public, max-age=31536000, immutable.

Beyond traditional search engines (robots.txt + sitemap.xml), the site implements Agentic Discovery through two machine-readable entrypoints with permissive CORS (Access-Control-Allow-Origin: *):

  1. /llms.txt (Content-Type: text/markdown; charset=utf-8): Provides LLM agents a concise Markdown map of bilingual routes (/, /en, /ar), featured platforms, GitHub profiles, and direct contact metadata.
  2. /.well-known/ard.json (Content-Type: application/json; charset=utf-8), linked in <head> via <link rel="ard" href="/.well-known/ard.json" />: Implements Agentic Resource Discovery (ARD v0.91) so agents can resolve canonical documentation directly:
# Summary of public/_headers & Agentic Discovery endpoints
security_headers:
  x_frame_options: "DENY"
  x_content_type_options: "nosniff"
  coop: "same-origin"
  csp_directives:
    default_src: "'self'"
    object_src: "'none'"
    frame_ancestors: "'none'"
    base_uri: "'self'"
immutable_cache_paths:
  - "/assets/*"
  - "/images/*"
  - "/og.webp"
agentic_endpoints:
  - path: "/llms.txt"
    content_type: "text/markdown; charset=utf-8"
    cors: "*"
  - path: "/.well-known/ard.json"
    content_type: "application/json; charset=utf-8"
    spec_version: "0.91"
    cors: "*"

By combining selective edge asset bypass, idle-deferred 24fps canvas rendering, build-time CSS inlining, responsive WebP preloading, strict CSP, and open agentic manifests (llms.txt + ARD), a bilingual SPA can stay visually expressive while behaving like a disciplined edge-first system.