0

My web application is accessible through multiple domains (example.com example.org example.net).

Question: How can I access the domain of the current route?

Please note: I use SSR (server side rendering), answer can therefore not include window or any other browser object.

Expected result: If application is accessed via example.org and current route is www.example.org/frontpage

const domain = await someFunction()
console.log(domain);
// example.org
Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • does that work for you? https://stackoverflow.com/questions/51984268/how-to-get-base-url-in-angular-5 –  Sep 03 '20 at 11:35
  • No, all answers would not work on a server environment (my application is rendered on the server (SSR)) – Vingtoft Sep 03 '20 at 11:43

1 Answers1

0

This worked for me. I get x-forwarded-host from the request this way:

In server.ts:

  server.get('*', (req, res) => {
    const xForwardedHost = req.headers['x-forwarded-host'];
    res.render(indexHtml, { req, providers: [
      { provide: APP_BASE_HREF, useValue: req.baseUrl },
      { provide: 'X_FORWARDED_HOST', useValue: xForwardedHost },
    ] });
  });

Then inject 'X_FORWARDED_HOST' where you need it, for instance:

export class AppComponent {
  constructor(
    @Optional() @Inject('X_FORWARDED_HOST') private host: any,

  ) {
    console.log('My host is',host);
  }
}

Since 'X_FORWARDED_HOST' was defined only in server.ts, it only exists in the server. In the browser it will be null, thats why you should use the @Optional() decorator, otherwise you are going to get an error.

Gabriel
  • 312
  • 1
  • 13