Angular 18 SSR with Strict CSP CSS issue

Discussão em 'Angular' iniciado por Sonu S, Abril 1, 2025.

  1. Sonu S

    Sonu S Guest

    I'm working on an Angular 18 application that uses SSR with separate browser and server builds (built via “ng build && ng run myapp:server” and served with “node dist/myapp/server/main.js”). My app uses NgModules (upgraded from Angular 15), and all global CSS are added via the styles array in angular.json.

    The Issue: On the initial full page load, the UI appears correct—even though I’ve implemented strict CSP by using a nonce (via the ngCspNonce attribute on my root and providing the nonce through the CSP_NONCE injection token). However, when I navigate to another page using Angular’s router, the UI breaks.

    What I’ve Considered:

    Critical CSS Inlining: Angular’s build optimizer might be inlining only “critical” CSS (using tools like Critters) during SSR, and on navigation the deferred CSS isn’t fully applied.

    "optimization": {
    "scripts": true,
    "styles": {
    "minify": false,
    "inlineCritical": false
    },
    "fonts": true
    },


    Hydration/Style Rehydration Bug: There might be a bug in Angular 18’s hydration process where inline styles generated during SSR aren’t re-injected or rehydrated correctly on client-side navigation.

    DOM Manipulation on Navigation: Angular’s router might be removing or replacing certain DOM nodes that hold the global CSS, and if these nodes aren’t reinserted with the correct nonce, some styles may be lost.

    Nonce/CSP Side Effects: Although the nonce is correctly inserted on a full refresh, Chrome’s stripping of nonce attributes might interfere with Angular’s logic for dynamically injecting or reusing CSS during navigation.

    What I’ve Tried/Considered as Solutions:

    I’ve ensured that the nonce value is provided via both the ngCspNonce attribute (without the literal “nonce-” prefix) and the CSP_NONCE injection token (sourced from a meta tag).

    I’m considering disabling inline critical CSS (setting "inlineCritical": false in angular.json) to force external CSS file loading.

    I’ve compared SSR and client-side rendered DOM snapshots and noticed the inconsistency in nonce application on inline style tags.

    How to fix this issue?

    Continue reading...

Compartilhe esta Página