karolix1279
karolix1279

Reputation: 33

How to inject nonce from express.js node to angular 19?

According to docs:

  1. Set the ngCspNonce attribute on the root application element as . Use this approach if you have access to server-side templating that can add the nonce both to the header and the index.html when constructing the response.
  2. Provide the nonce using the CSP_NONCE injection token. Use this approach if you have access to the nonce at runtime and you want to be able to cache the index.html.

However with new engine AngularNodeAppEngine i have no clue what should i do to achive this.

Upvotes: 2

Views: 74

Answers (1)

Naren Murali
Naren Murali

Reputation: 56002

In angular 19 can you try adding it to the providers array of serverConfig. This seems to generate the nonce when generating a build.

import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
import { CSP_NONCE } from '@angular/core';

const serverConfig: ApplicationConfig = {
  providers: [
    provideServerRendering(),
    {
      provide: CSP_NONCE,
      useValue: `default-src 'self'; style-src 'self' 'nonce-${Math.random()}'; script-src 'self' 'nonce-${Math.random()}';`,
    },
  ],
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

Stackblitz Demo -> cd test -> npm i -> npm run build -> do a global search in dist folder for nonce

Upvotes: 0

Related Questions