Search code examples
angularauth0

How to dynamically generate the Host URL in Angular (v. 4)


So I am using Auth0 and wanted to know how to dynamically generate the Host URL to set the redirectUri property of WebAuth() of auth0.

auth0 = new auth0.WebAuth({
  clientID: AUTH_CONFIG.clientID,
  domain: AUTH_CONFIG.domain,
  responseType: 'token id_token',
  audience: `https://${AUTH_CONFIG.domain}/userinfo`,
  redirectUri: 'http://localhost:4200/#/callback',
  scope: 'openid'
});

The purpose is that I don't want to hard-code my host address when switching environments or deploying Angular app. As you can see above I am hard-coding http://localhost:4200/#/ the redirectUri.

How do I do this?


Solution

  • You can just use window.location.origin. For example:

    auth0 = new auth0.WebAuth({
      clientID: AUTH_CONFIG.clientID,
      domain: AUTH_CONFIG.domain,
      responseType: 'token id_token',
      audience: `https://${AUTH_CONFIG.domain}/userinfo`,
      redirectUri: `${window.location.origin}/#/callback`,
      scope: 'openid'
    });