vlz
vlz

Reputation: 1039

Angular: How to set baseHref for assets in development when using SSR

In production we are setting the base href with:

ng build --base-href /app/

This works well. Especially our assets are also served at /app/assets/ as expected.

I cannot achieve the same effect in development however, where we run:

ng run project:serve-ssr

Assets remain at /assets and are not accessible at /app/assets.

Things I have tried in angular.json

I have also tried to set the DI token APP_BASE_HREF and provide it in the AppModue, but to no effect.

Upvotes: 0

Views: 1692

Answers (2)

gearsdigital
gearsdigital

Reputation: 14225

Assuming you are using @nguniversal we solved this by creating a virtual path prefix in server.ts:

server.use(process.emv.BASE_HREF, express.static(distFolder));

The BASE_HREF is set as an environment variable during app start:

BASE_HREF=/app ng run project:serve-ssr

Upvotes: 1

vlz
vlz

Reputation: 1039

I ended up, rewriting the url in the express server in development. Not super happy with that though, so if anybody has a better answer, I will happily accept that.

In server.ts:

if (environment.removeAssetsPrefix.length) {
  server.use((req, _, next) => {
    if (req.url.startsWith(environment.removeAssetsPrefix + '/assets/')) {
      req.url = req.url.substring(environment.removeAssetsPrefix.length);
    }
    next();
  });
}

In environment.ts:

export const environment = { 
  ...
  removeAssetsPrefix: '/app'
};

Upvotes: 0

Related Questions