# Backend 2 handoff (SEO, analytics, security, performance)

## What other roles can rely on

| Thing | How to use it |
|---|---|
| SEO head | Already in the layout: `<x-seo.head :page-key="$pageKey ?? null" :content="$c ?? null" />`. Error pages: `<x-seo.head title="Page not found" />` (adds `noindex, follow`, no canonical). |
| Page meta keys read from content files | `meta.title`, `meta.description`, `meta.og_image` (a `/media/...` path; old `https://idealers.net/wp-content/...` URLs are mapped automatically), optional `meta.og_title`, `meta.robots`, `meta.canonical`, `meta.breadcrumb`. If a key is missing, the original Yoast value from `app/Support/Seo/data/original-pages.php` is used. |
| CSP nonce | Every inline `<script>` / `<style>` on the public site needs `nonce="{{ $cspNonce }}"` (or `{{ Vite::cspNonce() }}`). `@vite` tags get it automatically. Inline `style="..."` attributes are allowed; inline event handlers (`onclick=`), `javascript:` URLs and `eval`/`new Function` are blocked. |
| Preload hints | `@push('head') <x-seo.preload :image="media($c('hero.image'))" :fonts="['/fonts/poppins-300.woff2']" /> @endpush` (LCP image gets `fetchpriority="high"`). |
| Analytics events | `data-track="event_name"` plus `data-track-plan="Basic"` etc. on any element. Automatic: `tel:`/`mailto:` clicks, Stripe links (`stripe_click`, plan = `data-plan` or link text), idealers.app links (`dealership_login`), links to `/request-demo/` and `/talk-to-sales/`, outbound links, `<video>` play/complete, 25/50/75/90 % scroll. JS API: `window.idealersTrack(name, params)`. |
| Consent contract | Unchanged from the outline: `window.dispatchEvent(new CustomEvent('idealers:consent', {detail: {analytics: true|false}}))` and `localStorage.idealers_consent`. Accepted stored values: JSON `{"analytics":true}` / `{"analytics":false}`, or the strings `accepted`/`granted`/`true` and `rejected`/`denied`/`false`. Optional `marketing` flag (defaults to the `analytics` value) controls Meta Pixel and ad storage. |
| Cache clearing | Full-page cache, sitemap and redirect map are cleared on `App\Events\ContentChanged` (Backend 1 already fires it). |
| No session on public pages | Public routes run without session, CSRF and cookie middleware (no cookie before consent, page cache possible). Do not use `session()`, `csrf_token()`, `@csrf`, `old()` or `$errors` in public views. |

## Requests

### Project manager

1. **Parity test gets 301 instead of 200.** Laravel's test client trims the trailing slash from every relative URL (`$this->get('/pricing/')` sends `/pricing`), and `/pricing` now correctly 301s to `/pricing/`. Fix in `tests/Feature/Parity/PageParityTest.php` (or once in `tests/TestCase.php` for everyone):

   ```php
   protected function prepareUrlForRequest($uri)
   {
       if (preg_match('#^https?://#i', $uri)) {
           return $uri;
       }
       return 'http://localhost'.(str_starts_with($uri, '/') ? $uri : '/'.$uri);
   }
   ```

   (Same override as in `tests/Feature/Seo/Concerns/UsesSeoFixtures.php`.) Alternative: `$this->followingRedirects()->get($path)`.
2. **Deployment guide**: copy the nginx block, Apache notes and the shared-hosting `.htaccess` below into `docs/DEPLOYMENT.md`. No scheduled task or queue job was added by Backend 2.
3. Launch checklist items for the owner are listed at the end of this file.

### Frontend 1 and Frontend 2

1. Any inline `<script>` or `<style>` must carry `nonce="{{ $cspNonce }}"`. No `onclick=`/`onload=` attributes, no `javascript:` links.
2. Lottie: use a build that does not call `eval`/`new Function` (for example `lottie_light` or `lottie-web/build/player/lottie_svg`), load animation JSON from `/media/...` (same origin).
3. The cookie notice must not set cookies itself (localStorage only, as agreed) so that the public site stays cookie-free.
4. Frontend 2: content files currently put the old `https://idealers.net/wp-content/...` URL in `meta.og_image`. It works (mapped automatically), but a `/media/...` path is cleaner.
5. Do not use Livewire components on public pages: Livewire injects un-nonced inline styles/scripts that the public CSP blocks (and they would need a session).
6. Optional: add `data-plan="Plan name"` on the Stripe buttons so `stripe_click` events carry the exact plan name.

### Backend 1

1. Keep firing `App\Events\ContentChanged` for every settings save (analytics IDs, verification codes, `seo.noindex_site` change the HTML and the CSP).
2. Site settings form: the new keys `analytics.hotjar_id` (old site used Hotjar 3840705) and the existing `analytics.meta_pixel_id` exist in `config/site.php`. Please expose them with the GA4/GTM fields, plus `seo.default_robots`. All four analytics IDs accept only letters, digits and dashes (anything else is ignored on output).
3. If the admin path is changed through `ADMIN_PATH`, the `admin` exclusion in `public/.htaccess` and the nginx block must be changed too (the middleware reads `config('admin.path')` automatically).

## nginx server block (for docs/DEPLOYMENT.md)

```nginx
# HTTP and www -> https://idealers.net
server {
    listen 80;
    listen [::]:80;
    server_name idealers.net www.idealers.net;
    return 301 https://idealers.net$request_uri;
}
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name www.idealers.net;
    ssl_certificate     /etc/letsencrypt/live/idealers.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/idealers.net/privkey.pem;
    return 301 https://idealers.net$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name idealers.net;

    root /var/www/idealers/public;     # document root = public/ ONLY
    index index.php;
    charset utf-8;
    server_tokens off;
    client_max_body_size 60m;          # admin video uploads (ADMIN_MAX_VIDEO_KB) + margin

    ssl_certificate     /etc/letsencrypt/live/idealers.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/idealers.net/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    # Compression
    gzip on;
    gzip_vary on;
    gzip_comp_level 5;
    gzip_types text/plain text/css text/xml application/xml application/javascript text/javascript application/json application/ld+json image/svg+xml application/manifest+json;
    # brotli on; brotli_types ...same list...   (if ngx_brotli is installed)

    # Dotfiles (except /.well-known) and sensitive file types
    location ~ /\.(?!well-known/) { deny all; return 404; }
    location ~* \.(bak|backup|old|orig|save|swp|sql|sqlite|db|log|ini|env|sh|lock|dist|ya?ml|md|phar|zip|tar|gz|7z)$ { deny all; return 404; }

    # Trailing-slash canonical URLs (WordPress style): /about -> /about/
    # Not for files with an extension, the admin, Livewire, assets or old wp- paths (Laravel answers those).
    location ~ ^/(?!admin|livewire|filament|build/|media/|fonts/|js/|css/|storage/|vendor/|up$|\.well-known/|wp-)[^.]*[^/]$ {
        if ($request_method ~ ^(GET|HEAD)$) { return 301 $uri/$is_args$args; }
        try_files $uri /index.php?$query_string;
    }

    # Long-lived caching for hashed build output and media
    location ^~ /build/ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; add_header X-Content-Type-Options nosniff; try_files $uri =404; }
    location ^~ /media/ { expires 1y; add_header Cache-Control "public, max-age=31536000, immutable"; add_header X-Content-Type-Options nosniff; try_files $uri @laravel; }
    location ^~ /fonts/ { expires 30d; add_header Cache-Control "public, max-age=2592000"; add_header Access-Control-Allow-Origin "*"; try_files $uri =404; }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location @laravel { rewrite ^ /index.php last; }

    # Only the front controller is executed
    location = /index.php {
        fastcgi_pass unix:/run/php/php8.5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }
    # Any other .php URL (/wp-login.php, /xmlrpc.php...) is never executed: it goes to
    # Laravel, which answers old WordPress URLs with 410 Gone.
    location ~ \.php$ { rewrite ^ /index.php last; }

    error_log  /var/log/nginx/idealers.error.log warn;
    access_log /var/log/nginx/idealers.access.log;
}
```

Also set `expose_php = Off` in php.ini (removes `X-Powered-By` at the source).

## Apache notes

- Virtual host `DocumentRoot` must be `/path/to/site/public` with `AllowOverride All` (the shipped `public/.htaccess` needs `FileInfo`, `Options`, `Indexes` and `mod_rewrite`; `mod_headers`, `mod_expires`, `mod_deflate` and optionally `mod_brotli` are used when present).
- `ServerTokens Prod` and `ServerSignature Off` in the main config, `expose_php = Off` in php.ini.
- HTTP -> HTTPS and www -> apex are also done by the app in production (`SECURITY_FORCE_HTTPS`, `SECURITY_FORCE_CANONICAL_HOST`), but doing it in the vhost saves a PHP hit:

  ```apache
  <VirtualHost *:80>
      ServerName idealers.net
      ServerAlias www.idealers.net
      Redirect permanent / https://idealers.net/
  </VirtualHost>
  ```

### Shared hosting where the document root cannot point at public/

Put this as `.htaccess` in the project root (next to `artisan`) so nothing outside `public/` is reachable:

```apache
Options -Indexes
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(\.env|\.git|storage|vendor|reference|database|app|config|bootstrap|resources|routes|tests|scripts|docs|node_modules)(/|$) - [F,L,NC]
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
<FilesMatch "^(\.env.*|composer\.(json|lock)|package(-lock)?\.json|artisan|phpunit\.xml|vite\.config\.js|.*\.md)$">
    Require all denied
</FilesMatch>
```

Prefer a real `DocumentRoot .../public` whenever possible.

## Behind a proxy / CDN

Set `TRUSTED_PROXIES` to the proxy IPs (Cloudflare ranges, load balancer IP), otherwise HTTPS detection, rate limiting per IP and HSTS do not work. Do not let a CDN cache HTML for more than its origin `Cache-Control` (`no-cache, private`): every HTML response carries a unique CSP nonce. `/build/*` and `/media/*` can be cached forever.

## Owner must supply at launch

- Google tag / GA4 measurement ID (`SITE_GA4_ID` or admin). The old site used Google tag **GT-5R7TZF6M** through Site Kit; confirm it is still the right property.
- Optional GTM container ID.
- Meta Pixel ID (old site: **263970003369260**) and Hotjar ID (old site: **3840705**) if they still want them. They load only after cookie consent.
- Google Search Console and Bing Webmaster verification codes (or keep DNS verification), then submit `https://idealers.net/sitemap.xml`.
- `SECURITY_CONTACT` for security.txt (defaults to `mailto:info@idealers.net`, the address the old site published).
- `TRUSTED_PROXIES` if hosted behind Cloudflare or a load balancer.
