diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c9ab3c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +tools/ +__pycache__/ +*.pyc diff --git a/README.md b/README.md index 62ae96d..d941578 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,43 @@ # news-platform -Scalable multi-domain sports news platform — frontend + WordPress bridge + SEO + LXC deploy. +Scalable multi-domain sports news platform — Astro 5 SSR frontend, Fastify bridge, headless WordPress. ## Structure ``` news-platform/ - frontend/ # Next.js or Vite frontend app - bridge/ # WordPress REST API bridge / adapter + frontend/ # Astro 5 SSR frontend application + bridge/ # Fastify bridge (WordPress REST API cache + normalizer) wordpress/ # WordPress config, themes, plugins config/domains/ # Per-domain configuration files docs/ # Architecture and runbooks deploy/ # LXC provisioning and deploy scripts - README.md ``` +## Quick Start + +```bash +# 1. Start WordPress + MySQL +cd wordpress && docker compose up -d + +# 2. Start bridge +cd bridge && npm install && npm run dev + +# 3. Start frontend +cd frontend && npm install && npm run dev +``` + +Open: http://localhost:4321 + +## Documentation + +- [Architecture + Stack Justification](docs/architecture.md) +- [Frontend (Astro 5)](docs/frontend.md) +- [Bridge (Fastify)](docs/bridge.md) +- [Multi-Domain Config](docs/domains.md) +- [SEO Strategy](docs/seo.md) +- [Deployment (LXC)](docs/deployment.md) + ## Related - Paperclip project: [News Platform](/BIT/projects/news-platform) diff --git a/config/domains/newsproject.bitreport.pt.json b/config/domains/newsproject.bitreport.pt.json new file mode 100644 index 0000000..81a642e --- /dev/null +++ b/config/domains/newsproject.bitreport.pt.json @@ -0,0 +1,25 @@ +{ + "site_name": "Sports News", + "site_description": "The best sports coverage in Portugal", + "theme": "sports", + "logo": "/assets/newsproject/logo.svg", + "favicon": "/assets/newsproject/favicon.ico", + "primary_color": "#e63946", + "categories": ["Football", "Basket", "F1", "Tennis", "Rugby"], + "nav_categories": ["Football", "Basket", "F1"], + "wp_endpoint": "http://wp.newsproject.local/wp-json", + "bridge_endpoint": "http://localhost:3200", + "locale": "pt_PT", + "timezone": "Europe/Lisbon", + "social": { + "twitter": "@sportsbitreport", + "facebook": "sportsbitreport" + }, + "ads": { + "enabled": false, + "provider": null + }, + "analytics": { + "ga4": null + } +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..40265d1 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,415 @@ +# News Platform — Architecture + +**Version:** 1.0 +**Date:** 2026-03-23 +**Author:** David Santos (Founding Engineer, BitReport) + +--- + +## Overview + +A scalable, multi-domain news platform designed for high traffic. Built on a headless architecture: Astro 5 SSR frontend, Fastify bridge layer, and WordPress as the headless CMS. The platform supports multiple domains without code changes — only per-domain JSON config files need to be added. + +--- + +## 1. Stack Selection and Justification + +### Decision: Astro 5 SSR + Fastify Bridge + Headless WordPress + +#### Framework Comparison + +| Criterion | Astro 5 SSR | Next.js 15 | Nuxt 3 | +|-----------|-------------|------------|--------| +| Default output | Static/SSR hybrid | SSR/CSR | SSR/CSR | +| JS sent to client | Near-zero by default | Significant (React hydration) | Moderate (Vue hydration) | +| TTFB (cached SSR) | Excellent | Good | Good | +| Core Web Vitals (CLS/LCP) | Best (minimal hydration) | Moderate (layout shift on hydrate) | Moderate | +| Multi-framework components | Yes (React, Vue, Svelte) | React only | Vue only | +| Static island hydration | Built-in (Islands Architecture) | Manual (RSC) | Manual (Suspense) | +| Cold-start (serverless) | Lower (small runtime) | Higher (React + Next core) | Moderate | +| SEO primitives | First-class | Good | Good | +| Build size | Minimal | Large | Moderate | +| Ecosystem maturity | Growing, stable API | Mature | Mature | + +**Why Astro 5 wins for a news platform:** + +1. **Islands Architecture by default.** The vast majority of a news page is static content (headline, article body, images). Astro only ships JS for interactive islands (e.g., search widget, ad slots). This directly improves LCP and TBT. + +2. **Near-zero JS on article pages.** Article pages account for ~90% of traffic on news sites. No hydration penalty means better Core Web Vitals at scale. + +3. **CDN/cache friendliness.** Astro pages render to clean HTML + minimal CSS. CDN edge caches store full responses. No runtime client-side fetch waterfalls. + +4. **Content Collections and SSR together.** Astro 5's SSR mode supports per-request server rendering while still allowing static prerendering for high-volume pages. Hybrid SSR/static per route. + +5. **Performance targets are achievable.** TTFB < 200 ms cached, LCP < 2.5 s, CLS < 0.1 are all attainable with Astro's default output. Next.js requires additional tuning (turbopack, RSC, `use client` discipline) to reach the same floor. + +6. **Multi-domain config is simple.** Astro reads domain from `Astro.request.headers.get('host')` in SSR mode — no framework-specific routing hacks needed. + +**Next.js trade-offs (why not chosen):** +- React hydration by default inflates JS payload +- App Router complexity (RSC + Server Actions) adds cognitive overhead not needed for a content site +- Bundle size is higher even for static pages + +**Nuxt trade-offs (why not chosen):** +- Vue ecosystem is smaller than React; fewer available UI component libraries for news/media layouts +- SSR cold start slightly heavier than Astro + +--- + +## 2. Component Diagram + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ User / Browser │ +└─────────────────────────┬───────────────────────────────────────┘ + │ HTTPS +┌─────────────────────────▼───────────────────────────────────────┐ +│ Cloudflare CDN / Edge Cache │ +│ (full-page HTML cache, static assets, image transforms) │ +└─────────────────────────┬───────────────────────────────────────┘ + │ Cache miss / dynamic +┌─────────────────────────▼───────────────────────────────────────┐ +│ Nginx Reverse Proxy (LXC) │ +│ (TLS termination, host routing → port 4321) │ +└─────────────────────────┬───────────────────────────────────────┘ + │ +┌─────────────────────────▼───────────────────────────────────────┐ +│ Astro 5 SSR Frontend (:4321) │ +│ │ +│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ +│ │ Domain config│ │ Page routes │ │ Island components │ │ +│ │ loader │ │ / │ │ (search, comments, │ │ +│ │ │ │ /[category] │ │ ad slots, menus) │ │ +│ └─────────────┘ │ /[cat]/[slug]│ └──────────────────────┘ │ +│ │ /sitemap.xml │ │ +│ │ /robots.txt │ │ +│ └──────────────┘ │ +└─────────────────────────┬───────────────────────────────────────┘ + │ HTTP (internal) +┌─────────────────────────▼───────────────────────────────────────┐ +│ Fastify Bridge (:3200) │ +│ │ +│ ┌───────────────┐ ┌─────────────┐ ┌────────────────────┐ │ +│ │ Domain → WP │ │ Redis cache │ │ Data normalizer │ │ +│ │ router │ │ layer │ │ (WP → canonical │ │ +│ │ │ │ (TTL: 60s) │ │ article model) │ │ +│ └───────────────┘ └─────────────┘ └────────────────────┘ │ +│ │ +│ Routes: GET /posts GET /posts/:slug GET /categories │ +│ GET /tags GET /search GET /sitemap │ +└─────────────────────────┬───────────────────────────────────────┘ + │ HTTP +┌─────────────────────────▼───────────────────────────────────────┐ +│ WordPress (headless, :8080) │ +│ │ +│ REST API /wp-json/wp/v2/ │ +│ posts, categories, tags, media, users │ +│ │ +│ No theme rendered — WP admin only for editorial. │ +└─────────────────────────┬───────────────────────────────────────┘ + │ +┌─────────────────────────▼───────────────────────────────────────┐ +│ Redis (:6379) │ +│ Bridge response cache (articles, category lists, menus) │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 3. Data Flow + +### Standard Article Page Request + +``` +Browser + → GET https://newsproject.bitreport.pt/futebol/porto-bate-benfica + → Cloudflare CDN checks edge cache + HIT → return cached HTML (TTFB: ~10–30 ms) + MISS → forward to Nginx + → Nginx → Astro SSR (:4321) + → Astro reads host header + → Loads config/domains/newsproject.bitreport.pt.json + → Fetches article: GET http://bridge:3200/posts?slug=porto-bate-benfica&domain=newsproject.bitreport.pt + → Fastify Bridge checks Redis key posts:newsproject:porto-bate-benfica + HIT → return normalized article (TTFB bridge: ~2 ms) + MISS → GET http://wp.newsproject.local/wp-json/wp/v2/posts?slug=porto-bate-benfica + → normalize response + → write to Redis (TTL: 60 s) + → return to Astro + → Astro renders full HTML page (SSR) + → Sets Cache-Control: s-maxage=60, stale-while-revalidate=300 + → Cloudflare caches response + → HTML returned to browser +``` + +### Cache Invalidation + +On WordPress `save_post` hook, a custom plugin calls: +``` +POST http://bridge:3200/cache/invalidate +{ "domain": "newsproject.bitreport.pt", "slug": "porto-bate-benfica" } +``` +This deletes the specific Redis keys and optionally triggers a Cloudflare Cache Purge API call. + +--- + +## 4. Multi-Domain Routing + +### Config File Structure + +``` +config/ + domains/ + newsproject.bitreport.pt.json + sports1.example.com.json +``` + +### Domain Config Schema + +```jsonc +{ + "site_name": "Sports News", + "site_description": "The best sports coverage in Portugal", + "theme": "sports", + "logo": "/assets/newsproject/logo.svg", + "favicon": "/assets/newsproject/favicon.ico", + "primary_color": "#e63946", + "categories": ["Football", "Basket", "F1", "Tennis", "Rugby"], + "nav_categories": ["Football", "Basket", "F1"], + "wp_endpoint": "http://wp.newsproject.local/wp-json", + "bridge_endpoint": "http://bridge:3200", + "locale": "pt_PT", + "timezone": "Europe/Lisbon", + "social": { + "twitter": "@sportsbitreport", + "facebook": "sportsbitreport" + }, + "ads": { + "enabled": false, + "provider": null + }, + "analytics": { + "ga4": null + } +} +``` + +### Astro Domain Resolution (SSR) + +```typescript +// src/lib/domain.ts +export async function loadDomainConfig(host: string) { + const sanitized = host.replace(/:\d+$/, ""); // strip port + const configPath = path.join("config/domains", `${sanitized}.json`); + if (!existsSync(configPath)) { + throw new Error(`No domain config found for: ${sanitized}`); + } + return JSON.parse(readFileSync(configPath, "utf-8")) as DomainConfig; +} +``` + +Adding a new domain requires only: +1. Create `config/domains/.json` +2. Configure DNS → same server +3. No code changes, no redeploy required (file is read at request time in SSR mode) + +--- + +## 5. SEO Strategy + +### Server-Side Rendering + +All pages are fully rendered server-side. Search engine crawlers receive complete HTML on first request — no JS execution required for indexing. + +### Schema.org Structured Data + +Article pages emit `NewsArticle` JSON-LD: + +```json +{ + "@context": "https://schema.org", + "@type": "NewsArticle", + "headline": "Porto bate Benfica no clássico", + "datePublished": "2026-03-23T12:00:00Z", + "dateModified": "2026-03-23T13:30:00Z", + "author": { "@type": "Person", "name": "João Silva" }, + "publisher": { + "@type": "Organization", + "name": "Sports News", + "logo": { "@type": "ImageObject", "url": "https://newsproject.bitreport.pt/logo.png" } + }, + "image": "https://newsproject.bitreport.pt/img/porto-benfica.jpg", + "url": "https://newsproject.bitreport.pt/futebol/porto-bate-benfica" +} +``` + +### URL Structure + +``` +/ Homepage +/[category]/ Category page +/[category]/[slug]/ Article page +/sitemap.xml Sitemap (generated dynamically from bridge) +/robots.txt Robots (generated per domain config) +/search?q=porto Search results (SSR + client island) +``` + +### Meta Tags (per page) + +```html +{title} | {site_name} + + + + + + + + + + + + + + + + +``` + +--- + +## 6. Performance Targets + +| Metric | Target | Strategy | +|--------|--------|----------| +| TTFB (cache HIT) | < 30 ms | Cloudflare edge cache | +| TTFB (cache MISS, cached bridge) | < 200 ms | Redis in bridge | +| TTFB (cold, WP fetch) | < 800 ms | Bridge normalizes quickly; WP is internal | +| LCP | < 2.5 s | SSR HTML, preload hero image, no hydration waterfall | +| CLS | < 0.1 | Reserve image dimensions, no layout-shifting ads on load | +| FID / INP | < 200 ms | Near-zero JS, islands only for interactive elements | +| Lighthouse Performance Score | ≥ 90 | SSR + minimal JS + image optimization | + +### Image Optimization + +- Astro's `` component: automatic WebP conversion, `width`/`height` attributes prevent CLS +- Cloudflare Image Resizing or self-hosted `sharp` proxy for thumbnails +- `loading="lazy"` on below-the-fold images; `fetchpriority="high"` on hero + +--- + +## 7. Caching Strategy + +### Layers + +| Layer | Technology | TTL | Scope | +|-------|-----------|-----|-------| +| CDN edge | Cloudflare | 60 s (s-maxage) + 300 s SWR | Full HTML pages, static assets | +| Bridge response cache | Redis | 60 s articles, 300 s categories | WP REST API responses | +| Astro page cache | In-process Map (optional) | 10 s | Repeated SSR renders for same page | +| HTTP Cache-Control | `s-maxage` + `stale-while-revalidate` | Set per route | Instructs CDN | + +### Cache Keys + +Bridge uses composite keys: +``` +posts:{domain}:{slug} → single article +posts-list:{domain}:{category}:{page} → category listing +categories:{domain} → navigation menu +sitemap:{domain} → sitemap data +``` + +### Invalidation Triggers + +1. WordPress `save_post` hook → Bridge `/cache/invalidate` endpoint +2. WordPress `delete_post` hook → Bridge `/cache/invalidate` + Cloudflare purge +3. Manual: `POST /cache/invalidate-all?domain=newsproject.bitreport.pt` + +--- + +## 8. Repository Structure + +``` +news-platform/ +├── frontend/ # Astro 5 SSR application +│ ├── src/ +│ │ ├── pages/ +│ │ │ ├── index.astro +│ │ │ ├── [category]/ +│ │ │ │ ├── index.astro +│ │ │ │ └── [slug].astro +│ │ │ ├── sitemap.xml.ts +│ │ │ └── robots.txt.ts +│ │ ├── components/ +│ │ │ ├── layout/ +│ │ │ ├── article/ +│ │ │ └── islands/ # Client-side interactive islands +│ │ ├── lib/ +│ │ │ ├── domain.ts +│ │ │ └── bridge.ts +│ │ └── styles/ +│ ├── astro.config.mjs +│ └── package.json +│ +├── bridge/ # Fastify bridge API +│ ├── src/ +│ │ ├── routes/ +│ │ ├── services/ +│ │ │ ├── wordpress.ts +│ │ │ └── cache.ts +│ │ └── normalizers/ +│ │ └── post.ts +│ ├── package.json +│ └── tsconfig.json +│ +├── wordpress/ # WP config and custom plugins +│ ├── plugins/ +│ │ └── bridge-invalidator/ +│ └── docker-compose.yml +│ +├── config/ +│ └── domains/ +│ └── newsproject.bitreport.pt.json +│ +├── deploy/ +│ ├── nginx/ +│ │ └── newsproject.conf +│ └── lxc/ +│ └── setup.sh +│ +└── docs/ + ├── architecture.md # This file + ├── frontend.md + ├── bridge.md + ├── domains.md + ├── seo.md + └── deployment.md +``` + +--- + +## 9. Infrastructure Overview + +See [docs/deployment.md](./deployment.md) for full LXC setup. + +- **LXC container:** `news-project-test` on Proxmox, Ubuntu 24.04 +- **CPU:** 2 cores, **RAM:** 4 GB, **Disk:** 20 GB +- **Domain:** `newsproject.bitreport.pt` (NPM configured by user) +- **Services:** Nginx, Node.js (Astro + Fastify), WordPress (Docker), Redis, MySQL + +--- + +## 10. Future Scalability + +The current architecture supports future growth without structural changes: + +| Future requirement | How it is supported | +|-------------------|---------------------| +| Multiple domains | Add `config/domains/.json` — no code change | +| Multiple WordPress instances | Bridge routes by domain → different `wp_endpoint` per config | +| Horizontal frontend scaling | Astro is stateless SSR — add nodes behind Nginx upstream | +| CDN multi-region | Cloudflare global edge already handles it | +| Multi-language | `locale` field in domain config; i18n routes (`/en/`, `/pt/`) per domain | +| Ad network integration | Islands architecture: drop ad island component per placement | +| Multi-theme | `theme` field in domain config; Astro layout resolves theme component set | +| AMP | Optional: Astro can render AMP-compliant output per route (`/amp/[slug]`) | diff --git a/docs/bridge.md b/docs/bridge.md new file mode 100644 index 0000000..cca6efe --- /dev/null +++ b/docs/bridge.md @@ -0,0 +1,125 @@ +# Bridge — Fastify API Layer + +> **Status:** Stub — implementation in progress (BIT-345) + +--- + +## Overview + +The bridge is a lightweight Fastify HTTP server that sits between the Astro frontend and WordPress. It abstracts WordPress, normalizes data into a canonical article model, and caches responses in Redis. A single bridge instance can serve multiple domains (each mapped to a different WordPress instance via domain config). + +--- + +## Responsibilities + +- Route requests to the correct WordPress endpoint per domain +- Cache WP REST API responses in Redis +- Normalize WordPress post/category/tag responses into a canonical model +- Expose cache invalidation endpoints (called by WP `save_post` hook) +- Isolate the frontend from WP REST API changes + +--- + +## Tech Stack + +| Layer | Choice | +|-------|--------| +| HTTP server | Fastify 5 | +| Language | TypeScript (Node.js 22+) | +| Cache | Redis (ioredis) | +| HTTP client | `undici` | +| Process manager | PM2 or systemd | + +--- + +## Directory Structure + +``` +bridge/ +├── src/ +│ ├── server.ts # Fastify instance +│ ├── routes/ +│ │ ├── posts.ts +│ │ ├── categories.ts +│ │ ├── search.ts +│ │ ├── sitemap.ts +│ │ └── cache.ts # Invalidation endpoints +│ ├── services/ +│ │ ├── wordpress.ts # WP REST client +│ │ └── cache.ts # Redis wrapper +│ ├── normalizers/ +│ │ ├── post.ts # WP post → Article +│ │ └── category.ts # WP category → Category +│ └── config/ +│ └── domain.ts # Domain → WP endpoint resolver +├── package.json +└── tsconfig.json +``` + +--- + +## API Routes + +| Method | Path | Description | +|--------|------|-------------| +| `GET` | `/posts?domain=&page=&per_page=` | List posts | +| `GET` | `/posts/:slug?domain=` | Single post by slug | +| `GET` | `/categories?domain=` | Category list | +| `GET` | `/tags?domain=` | Tag list | +| `GET` | `/search?domain=&q=` | Full-text search | +| `GET` | `/sitemap?domain=` | All posts for sitemap | +| `POST` | `/cache/invalidate` | Invalidate specific key | +| `POST` | `/cache/invalidate-all` | Flush all keys for domain | + +--- + +## Canonical Article Model + +```typescript +interface Article { + id: number; + slug: string; + title: string; + excerpt: string; + content: string; // sanitized HTML + published_at: string; // ISO 8601 + modified_at: string; + author: { id: number; name: string }; + featured_image: { url: string; alt: string; width: number; height: number } | null; + categories: { id: number; slug: string; name: string }[]; + tags: { id: number; slug: string; name: string }[]; + canonical_url: string; +} +``` + +--- + +## Caching + +See [architecture.md#7-caching-strategy](./architecture.md#7-caching-strategy). + +Redis key pattern: `{type}:{domain}:{identifier}` + +Examples: +- `post:newsproject.bitreport.pt:porto-bate-benfica` +- `posts-list:newsproject.bitreport.pt:futebol:1` +- `categories:newsproject.bitreport.pt` + +--- + +## Development + +```bash +cd bridge +npm install +npm run dev # localhost:3200 (tsx watch) +npm run build # tsc → dist/ +npm run test # Vitest +``` + +Environment variables: + +```env +REDIS_URL=redis://localhost:6379 +PORT=3200 +``` diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..e4338c0 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,192 @@ +# Deployment — LXC on Proxmox + +> **Status:** Stub — implementation in progress (BIT-345) + +--- + +## Overview + +The platform runs on a single LXC container on Proxmox for the initial test deployment. The container hosts all services: Nginx reverse proxy, Astro frontend (Node.js), Fastify bridge (Node.js), WordPress (Docker), MySQL (Docker), and Redis. + +--- + +## LXC Container Spec + +| Property | Value | +|----------|-------| +| Name | `news-project-test` | +| OS | Ubuntu 24.04 LTS | +| CPU | 2 cores | +| RAM | 4 GB | +| Disk | 20 GB | +| Network | Bridge (vmbr0), DHCP or static IP | +| Domain | `newsproject.bitreport.pt` | + +--- + +## Service Layout + +``` +LXC: news-project-test +│ +├── nginx (host) :80, :443 +│ └── reverse proxy → :4321 (Astro) +│ +├── astro-frontend (PM2 / systemd) :4321 +│ └── node dist/server/entry.mjs +│ +├── fastify-bridge (PM2 / systemd) :3200 +│ └── node dist/server.js +│ +├── redis (host or Docker) :6379 +│ +└── Docker Compose + ├── wordpress :8080 + └── mysql :3306 (internal only) +``` + +--- + +## Setup Script (deploy/lxc/setup.sh) + +```bash +#!/bin/bash +set -euo pipefail + +# System +apt-get update && apt-get upgrade -y +apt-get install -y curl git nginx redis-server docker.io docker-compose-plugin + +# Node.js 22 +curl -fsSL https://deb.nodesource.com/setup_22.x | bash - +apt-get install -y nodejs + +# PM2 +npm install -g pm2 + +# Redis (start + enable) +systemctl enable --now redis-server + +# Docker +systemctl enable --now docker + +echo "Base setup complete. Deploy services manually or run per-service scripts." +``` + +--- + +## Nginx Config (deploy/nginx/newsproject.conf) + +```nginx +server { + listen 80; + server_name newsproject.bitreport.pt; + + location / { + proxy_pass http://127.0.0.1:4321; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + } +} +``` + +HTTPS/TLS is terminated at Nginx Proxy Manager (NPM), which the user configures manually. + +--- + +## WordPress (Docker Compose) + +```yaml +# wordpress/docker-compose.yml +services: + db: + image: mysql:8.0 + environment: + MYSQL_ROOT_PASSWORD: secret + MYSQL_DATABASE: wordpress + MYSQL_USER: wp + MYSQL_PASSWORD: wp_secret + volumes: + - db_data:/var/lib/mysql + + wordpress: + image: wordpress:6.7-php8.3-apache + depends_on: + - db + ports: + - "8080:80" + environment: + WORDPRESS_DB_HOST: db + WORDPRESS_DB_NAME: wordpress + WORDPRESS_DB_USER: wp + WORDPRESS_DB_PASSWORD: wp_secret + WORDPRESS_CONFIG_EXTRA: | + define('WP_HOME', 'http://wp.newsproject.local'); + define('WP_SITEURL', 'http://wp.newsproject.local'); + volumes: + - wp_data:/var/www/html + - ./plugins:/var/www/html/wp-content/plugins/custom + +volumes: + db_data: + wp_data: +``` + +--- + +## Service Start (PM2) + +```bash +# Frontend +cd /opt/news-platform/frontend +pm2 start dist/server/entry.mjs --name astro-frontend -- --port 4321 + +# Bridge +cd /opt/news-platform/bridge +pm2 start dist/server.js --name fastify-bridge -- --port 3200 + +pm2 save +pm2 startup +``` + +--- + +## Deployment Checklist + +- [ ] LXC container created and running +- [ ] Base packages installed (Node 22, nginx, redis, docker) +- [ ] Git repo cloned to `/opt/news-platform/` +- [ ] `config/domains/newsproject.bitreport.pt.json` populated +- [ ] Bridge dependencies installed and built +- [ ] Frontend dependencies installed and built +- [ ] WordPress Docker stack running (`docker compose up -d`) +- [ ] WordPress configured (admin user, permalink structure `/%category%/%postname%/`) +- [ ] Bridge invalidator plugin activated in WP +- [ ] PM2 processes started and saved +- [ ] Nginx config symlinked and nginx reloaded +- [ ] DNS points `newsproject.bitreport.pt` to container IP +- [ ] NPM configured for HTTPS (user step) +- [ ] Smoke test: `curl https://newsproject.bitreport.pt/` returns HTML +- [ ] Sitemap accessible at `/sitemap.xml` + +--- + +## Future: Multi-Container + +When the platform scales beyond a single test container, each service moves to its own LXC or VM: + +| Service | Container | +|---------|-----------| +| Astro frontend | `news-frontend-01`, `news-frontend-02` | +| Fastify bridge | `news-bridge-01` | +| WordPress | `news-wp-01` | +| MySQL | `news-db-01` | +| Redis | `news-redis-01` | +| Nginx LB | `news-lb-01` | + +Cloudflare sits in front of the load balancer. diff --git a/docs/domains.md b/docs/domains.md new file mode 100644 index 0000000..306c99d --- /dev/null +++ b/docs/domains.md @@ -0,0 +1,111 @@ +# Multi-Domain Configuration + +> **Status:** Stub — implementation in progress (BIT-345) + +--- + +## Overview + +The platform supports multiple domains without code changes. Each domain has a JSON config file in `config/domains/`. The Astro frontend reads the config at request time based on the `host` header; the bridge routes to the correct WordPress endpoint using the same config. + +--- + +## Adding a New Domain + +1. Create `config/domains/.json` (see schema below) +2. Configure DNS to point the domain at the server +3. If WordPress is a new instance, deploy it and update `wp_endpoint` +4. No code change. No redeploy. (In SSR mode, Astro reads configs from disk per request.) + +--- + +## Config Schema + +```jsonc +{ + // Identity + "site_name": "Sports News", + "site_description": "The best sports coverage in Portugal", + + // Visual + "theme": "sports", // maps to src/themes// + "logo": "/assets/newsproject/logo.svg", + "favicon": "/assets/newsproject/favicon.ico", + "primary_color": "#e63946", + + // Navigation + "categories": ["Football", "Basket", "F1", "Tennis", "Rugby"], + "nav_categories": ["Football", "Basket", "F1"], + + // Backend endpoints + "wp_endpoint": "http://wp.newsproject.local/wp-json", + "bridge_endpoint": "http://bridge:3200", + + // Locale + "locale": "pt_PT", + "timezone": "Europe/Lisbon", + + // Social + "social": { + "twitter": "@handle", + "facebook": "page-name" + }, + + // Features (future) + "ads": { "enabled": false, "provider": null }, + "analytics": { "ga4": null } +} +``` + +--- + +## Current Domains + +| Domain | Config file | WordPress | +|--------|-------------|-----------| +| `newsproject.bitreport.pt` | `newsproject.bitreport.pt.json` | `http://wp.newsproject.local` | + +--- + +## Domain Resolution in Astro + +```typescript +// src/lib/domain.ts +import { readFileSync, existsSync } from "node:fs"; +import path from "node:path"; + +export function loadDomainConfig(host: string): DomainConfig { + const hostname = host.replace(/:\d+$/, ""); + const configPath = path.join(process.cwd(), "config/domains", `${hostname}.json`); + + if (!existsSync(configPath)) { + throw new Error(`Domain config not found: ${hostname}`); + } + + return JSON.parse(readFileSync(configPath, "utf-8")) as DomainConfig; +} +``` + +Usage in an Astro page: + +```astro +--- +// src/pages/index.astro +import { loadDomainConfig } from "../lib/domain"; + +const host = Astro.request.headers.get("host") ?? "localhost"; +const config = loadDomainConfig(host); +--- + + {config.site_name} + ... + +``` + +--- + +## Notes + +- Domain config files are **not secrets** — they contain only public-facing site settings +- WordPress endpoints in `wp_endpoint` are internal network addresses; they must not be exposed publicly +- Theme names map to a directory under `frontend/src/themes/`; if a theme is missing, the default theme is used diff --git a/docs/frontend.md b/docs/frontend.md new file mode 100644 index 0000000..94d93ed --- /dev/null +++ b/docs/frontend.md @@ -0,0 +1,98 @@ +# Frontend — Astro 5 SSR + +> **Status:** Stub — implementation in progress (BIT-345) + +--- + +## Overview + +The frontend is an Astro 5 SSR application. It renders all pages server-side, resolves the active domain config at request time, fetches data from the Fastify bridge, and returns complete HTML to the client. + +--- + +## Tech Stack + +| Layer | Choice | +|-------|--------| +| Framework | Astro 5 (SSR mode, `output: 'server'`) | +| Adapter | `@astrojs/node` | +| UI components | Astro components + minimal React islands | +| Styling | Tailwind CSS v4 | +| Fonts | Self-hosted (no Google Fonts CDN) | +| Build | `astro build` → Node.js server | + +--- + +## Directory Structure + +``` +frontend/ +├── src/ +│ ├── pages/ +│ │ ├── index.astro # Homepage +│ │ ├── [category]/ +│ │ │ ├── index.astro # Category listing +│ │ │ └── [slug].astro # Article page +│ │ ├── search.astro # Search results +│ │ ├── sitemap.xml.ts # Dynamic sitemap +│ │ └── robots.txt.ts # Dynamic robots.txt +│ ├── components/ +│ │ ├── layout/ +│ │ │ ├── Header.astro +│ │ │ ├── Footer.astro +│ │ │ └── BaseLayout.astro +│ │ ├── article/ +│ │ │ ├── ArticleCard.astro +│ │ │ ├── ArticleBody.astro +│ │ │ └── ArticleMeta.astro +│ │ ├── home/ +│ │ │ ├── HeroBlock.astro +│ │ │ ├── TrendingBlock.astro +│ │ │ └── CategoryBlock.astro +│ │ └── islands/ +│ │ ├── SearchWidget.tsx # React island (client:load) +│ │ └── MobileMenu.tsx # React island (client:load) +│ ├── lib/ +│ │ ├── domain.ts # Domain config loader +│ │ ├── bridge.ts # Bridge API client +│ │ └── seo.ts # Meta tag helpers +│ └── styles/ +│ └── global.css +├── astro.config.mjs +├── tailwind.config.mjs +└── package.json +``` + +--- + +## Domain Resolution + +See [architecture.md#4-multi-domain-routing](./architecture.md#4-multi-domain-routing). + +--- + +## Performance Notes + +- All pages are SSR — no client-side data fetching waterfalls +- Interactive components are Astro Islands (only hydrate when needed) +- Hero images use `fetchpriority="high"` and `` for WebP/AVIF +- Tailwind output is purged — CSS < 20 KB per page +- `Cache-Control: s-maxage=60, stale-while-revalidate=300` set on article pages + +--- + +## Development + +```bash +cd frontend +npm install +npm run dev # localhost:4321 +npm run build # production build +npm run preview # preview production build +``` + +Environment variables: + +```env +BRIDGE_URL=http://localhost:3200 +``` diff --git a/docs/seo.md b/docs/seo.md new file mode 100644 index 0000000..b9b1c43 --- /dev/null +++ b/docs/seo.md @@ -0,0 +1,175 @@ +# SEO — Strategy and Implementation + +> **Status:** Stub — implementation in progress (BIT-345) + +--- + +## Overview + +SEO is a first-class concern for this platform. All pages are server-rendered, so search engines receive complete HTML without running JavaScript. The SEO implementation follows the standards used by top-tier news sites (Record, BBC Sport, The Athletic). + +--- + +## Principles + +1. **SSR-first.** No client-side rendering for content. Crawlers see full HTML. +2. **Canonical URLs.** Every page has one canonical URL; duplicates redirect (301). +3. **Structured data.** `NewsArticle` JSON-LD on all article pages. +4. **Fast first paint.** LCP < 2.5 s; CLS < 0.1 — both are Core Web Vitals ranking signals. +5. **Domain-aware.** Each domain generates its own sitemap, robots.txt, and meta tags. + +--- + +## URL Structure + +| Page type | URL pattern | +|-----------|-------------| +| Homepage | `/` | +| Category | `/{category}/` | +| Article | `/{category}/{slug}/` | +| Tag | `/tag/{slug}/` | +| Search | `/search?q={query}` | +| Sitemap | `/sitemap.xml` | +| Robots | `/robots.txt` | + +--- + +## Meta Tags + +Every page renders the following in ``: + +```html + +{title} | {site_name} + + + + + + + + + + + + + + + + + + + + + + + + +``` + +--- + +## Structured Data (JSON-LD) + +### Article Page + +```json +{ + "@context": "https://schema.org", + "@type": "NewsArticle", + "headline": "{title}", + "description": "{excerpt}", + "image": ["{featured_image_url}"], + "datePublished": "{published_at}", + "dateModified": "{modified_at}", + "author": { + "@type": "Person", + "name": "{author.name}" + }, + "publisher": { + "@type": "Organization", + "name": "{site_name}", + "logo": { + "@type": "ImageObject", + "url": "{logo_url}" + } + }, + "mainEntityOfPage": { + "@type": "WebPage", + "@id": "{canonical_url}" + }, + "breadcrumb": { + "@type": "BreadcrumbList", + "itemListElement": [ + { "@type": "ListItem", "position": 1, "name": "Home", "item": "{site_url}" }, + { "@type": "ListItem", "position": 2, "name": "{category}", "item": "{category_url}" }, + { "@type": "ListItem", "position": 3, "name": "{title}" } + ] + } +} +``` + +### Homepage / Site-wide + +```json +{ + "@context": "https://schema.org", + "@type": "WebSite", + "name": "{site_name}", + "url": "{site_url}", + "potentialAction": { + "@type": "SearchAction", + "target": "{site_url}/search?q={search_term_string}", + "query-input": "required name=search_term_string" + } +} +``` + +--- + +## Sitemap + +Generated dynamically at `/sitemap.xml` via Astro's `sitemap.xml.ts` endpoint. The bridge provides all published post slugs, categories, and tags. The sitemap is split by content type and updated on every request (cached 5 min in Redis). + +```xml + + + + https://newsproject.bitreport.pt/futebol/porto-bate-benfica/ + 2026-03-23T12:00:00Z + weekly + 0.8 + + ... + +``` + +--- + +## Robots.txt + +Generated dynamically at `/robots.txt` per domain: + +``` +User-agent: * +Allow: / +Disallow: /search +Disallow: /api/ + +Sitemap: https://newsproject.bitreport.pt/sitemap.xml +``` + +--- + +## Image SEO + +- All images have `alt` text (sourced from WP media library `alt` field) +- Featured images include `width` and `height` attributes (no CLS) +- Astro `` component generates WebP with JPEG fallback +- Hero image uses `fetchpriority="high"` to prioritize LCP element + +--- + +## AMP (Research Note) + +AMP is **not** in the initial scope. Astro can generate AMP-compliant pages via a parallel route (`/amp/[slug].astro`). Google no longer requires AMP for Top Stories eligibility (since 2021), so the ROI is low. Revisit if analytics show significant AMP traffic from legacy search placements.