PatentLobster
PatentLobster

Reputation: 13

Angular universal SSR dynamic absolute base-herf path

Hey I have App based on this starter kit

I deploy my app with the SSR feature from server.ts.

and the app is being served "dynamically" with Apache reverse proxy to localhost:4002 for multiple domains.

I.e domainA.com and domainB.com point to the same localhost:4002 with rev proxy. All the domains use the same App instance So far so good.

But now I've got a requirement for it to work under our partner reverse proxy which will look something like this partner.com/app/ will reverse proxy to partner.domainA.com

Which causes a lot of problems when loading the JS.

Currently the base-href is set to / which works on our sites great. but when a user goes to partner.com/app the browser tries to load all the JS assets from partner.com/*.js while the are only available on partner.com/app/*.js or partner.domainA.com/*.js.

My possible solution is to set APP_BASE_HERF from the server.ts when the request arrives.

But every thing I tried didn't seem to work.

I tried following this guide but it didn't seem to work and it was loading the url from the window object while I need to set it from the origin host which is available only from req.headers.host

in server.ts:

  res.render(
'../dist/index',
{
  req: req,
  res: res,
  // provers from server
  providers: [
    // for http and cookies
    {
      provide: REQUEST,
      useValue: req,
    },
    {
      provide: RESPONSE,
      useValue: res,
    },
    /// for cookie
    {
      provide: NgxRequest,
      useValue: req,
    },
    {
      provide: NgxResponce,
      useValue: res,
    },
    // for absolute path
    {
      provide: 'ORIGIN_URL',
      useValue: `${http}://${req.headers.host}`,
    },
  ],
},

is there a way to put the ORIGIN_URL in index.html base-herf? What is the correct way to set the base-herf in that way?

Thanks

Upvotes: 1

Views: 3298

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

Change your main.ts to :-

 window['base-href'] = window.location.pathname;
 if (env.production) {
    enableProdMode();
 }
 platformBrowserDynamic().bootstrapModule(AppModule);

in the above code, change url to where your base-href json is.

in appModule add this provider :-

providers: [
  {
    provide: APP_BASE_HREF,
    useValue: window['base-href']
  }
  ]

Upvotes: 1

Related Questions