wacrm/next.config.ts
Arnas Donauskas 0fa06d8b14
feat(i18n): harden build artifact tracing for Hostinger deploy
Re-applies PR #182's next-intl scaffold with defensive measures aimed
at the most-likely-but-unconfirmed causes of the 503 that hit prod
after that PR merged. PR #183 reverted #182 to restore service; this
branch carries the same i18n payload plus the safeguards below.

Defensive changes vs PR #182:

1. **`outputFileTracingRoot: __dirname`** in next.config.ts.
   Builds were warning that Next.js inferred the workspace root as
   the parent GHWebhosting directory (because of a stray lockfile
   there). With the wrong root, file tracing for the production
   artifact can include the wrong files or skip ours. Pinning the
   root to the wacrm directory silences the warning and makes tracing
   deterministic across local / CI / Hostinger.

2. **`outputFileTracingIncludes: { "/**/*": ["./messages/**/*.json"] }`**.
   Belt-and-suspenders: explicitly force the i18n message dictionaries
   into the production artifact even if static-import tracing somehow
   misses them in Hostinger's build environment.

3. **Static locale import map in `src/i18n/request.ts`**.
   Replaces `import(\`../../messages/\${locale}.json\`)` with an
   explicit `{ en: () => import(...), es: ..., lt: ... }` map.
   Template-literal dynamic imports are well-supported by Turbopack's
   tracer but the static form leaves zero room for the tracer to
   skip a locale.

4. **Try/catch around the intl middleware call**.
   If `intlMiddleware(request)` ever throws at runtime, fall through
   to auth-only handling and log the error rather than 503-ing every
   page request behind a single bad call.

5. **Try/catch around `LOADERS[locale]()`** with English fallback.
   Same idea: a missing locale bundle at runtime returns English
   content instead of crashing the render path.

6. **`engines.node: ">=20.10.0"`** (was `>=20.0.0`). Next 16.2's
   actual minimum. Tells Hostinger's Node.js app picker not to land
   us on a too-old subversion.

Verified locally:
- npm run lint → 0 errors (same 18 pre-existing warnings)
- npm run typecheck → clean
- npm run test → 366 passing
- npm run build → 62 prerendered pages across en/es/lt; workspace
  root warning gone; messages bundled into `.next/server/chunks/ssr/
  messages_{en,es,lt}_json_[json]_cjs_*.js`
- npm start probes:
    /              → 307 → /en
    /en/login      → 200
    /es/login      → 200
    /lt/login      → 200
    /en/dashboard  → 307 → /en/login (signed out)
    /api/whatsapp/templates → 401

If 503 reappears in prod after this lands, the local repro is clean,
so the next step is hPanel build/runtime logs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31 21:01:13 +03:00

149 lines
5.7 KiB
TypeScript

import path from "node:path";
import createNextIntlPlugin from "next-intl/plugin";
import type { NextConfig } from "next";
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
/**
* Baseline security headers applied to every response.
*
* CSP ships as `Content-Security-Policy-Report-Only` so the browser
* surfaces violations in the console without blocking anything — once
* we have confidence nothing legit trips it (two deploys, a pass on
* every route), flip the key to `Content-Security-Policy` to enforce.
*
* The rest of the headers are straight blocks, safe to enforce today:
* - HSTS: only meaningful on HTTPS (no-op on http://localhost).
* - X-Content-Type-Options / X-Frame-Options / Referrer-Policy:
* baseline OWASP hardening, no behavioural cost.
* - Permissions-Policy: we don't use camera / microphone / etc, so
* deny them. A supply-chain compromise or a forgotten plugin
* can't silently opt back in.
*/
const SECURITY_HEADERS = [
{
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubDomains; preload",
},
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=(), payment=(), usb=()",
},
{
key: "Content-Security-Policy-Report-Only",
value: [
"default-src 'self'",
// Next.js needs 'unsafe-inline' for its inline hydration script
// and 'unsafe-eval' in dev + some production optimisations.
// Nonce-based CSP is a later project.
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
// Tailwind + inline style attributes on lots of components.
"style-src 'self' 'unsafe-inline'",
// Supabase public-bucket avatars, contact avatars (arbitrary
// https URLs paste-able from the UI), OG images, data URLs for
// tiny inline assets.
"img-src 'self' data: blob: https:",
"font-src 'self' data:",
// Supabase REST + realtime (WSS). All Meta API calls happen
// server-side, so graph.facebook.com does not belong here.
"connect-src 'self' https://*.supabase.co wss://*.supabase.co",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
].join("; "),
},
] as const;
const nextConfig: NextConfig = {
// Pin file-tracing to this directory so Next.js doesn't ascend to the
// parent GHWebhosting folder (which has its own lockfile) and either
// bundle the wrong stuff or skip ours. Was visible as a workspace-root
// warning during builds. Also see `outputFileTracingIncludes` below —
// a wrong root makes the includes match incorrectly.
outputFileTracingRoot: path.join(__dirname),
// Force the production artifact to include the i18n message dictionaries.
// `src/i18n/request.ts` loads them via a static import map but the
// tracer can still miss JSON-only files that no code statically
// imports relative to this entry point. Belt-and-suspenders.
outputFileTracingIncludes: {
"/**/*": ["./messages/**/*.json"],
},
/**
* Cache-Control policy.
*
* Why this exists:
* Hostinger's CDN was applying `s-maxage=31536000` (1 year) to
* prerendered HTML pages by default. When a new deploy shipped
* fresh Turbopack chunk hashes, the edge kept serving year-old
* HTML referencing chunk filenames that no longer existed on
* disk — result: HTML 200, every /_next/static/*.js and .css
* came back 404, the page rendered unstyled. Private/incognito
* did nothing because the cache is server-side.
*
* Strategy:
* - /_next/static/* — immutable for a year. Filenames are
* content-hashed, so a new build produces new filenames; the
* old ones are safe to keep indefinitely in caches.
* - /api/* — no-store. API responses are per-user and
* must never be shared across requests at the edge.
* - Everything else — public, brief s-maxage + generous
* stale-while-revalidate. The edge serves instantly from cache
* for the first 5 min, then returns cached content while
* refreshing in the background for up to 24 h. A deploy's
* chunk-hash drift self-heals within ~5 min with no user-
* visible latency.
*
* Note: dynamic dashboard routes (/inbox, /contacts, /pipelines,
* /broadcasts, etc.) are server-rendered per request — Next.js
* and Supabase auth already prevent them from being served
* from a shared cache. The s-maxage here is a ceiling; Next.js
* and auth middleware still set `private` / `no-store` for
* per-user responses.
*
* Security headers are appended via a separate catch-all rule
* below — Next.js merges headers from every matching rule, so
* they apply to every response regardless of which cache rule
* matched.
*/
async headers() {
return [
{
source: "/_next/static/:path*",
headers: [
{
key: "Cache-Control",
value: "public, max-age=31536000, immutable",
},
],
},
{
source: "/api/:path*",
headers: [{ key: "Cache-Control", value: "no-store" }],
},
{
source: "/:path*",
headers: [
{
key: "Cache-Control",
value:
"public, max-age=0, s-maxage=300, stale-while-revalidate=86400",
},
],
},
{
// Security headers on every response, including /_next/static
// assets (nosniff matters there) and /api/* (HSTS + referrer-
// policy don't hurt).
source: "/:path*",
headers: [...SECURITY_HEADERS],
},
];
},
};
export default withNextIntl(nextConfig);