angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Deprecation of 'deployUrl' will/has caused the HashLocation routing to break when the baseHref is not on the same domain

Open djhouseknecht opened this issue 4 years ago • 3 comments

🐞 Bug report

Command (mark with an x)

  • [ ] new
  • [x] build
  • [ ] serve
  • [ ] test
  • [ ] e2e
  • [ ] generate
  • [ ] add
  • [ ] update
  • [ ] lint
  • [ ] extract-i18n
  • [ ] run
  • [ ] config
  • [ ] help
  • [ ] version
  • [ ] doc

Is this a regression?

In v13 of Angular, the deployUrl was deprecated and users were encouraged to use the base tag (ie. baseHref) instead.

baseHref and the router only seem to work if the assets are served from the same domain as the index.html (ie. "the index file"). This greatly limits and even blocks some Angular applications.

There are timeswhen the actual index file of the app is hosted on a separate domain.

Description

Given the following criteria:

  • The build Angular app's assets are uploaded to a cdn.
    • Example: https://s3.cdn.com/my-angular-app/build-123/<contents-of-the-dist-folder>
  • The index.html file of the app is then "deployed" to a separate domain.
    • Example: https://s3.cdn.com/my-angular-app/build-123/index.html is moved to https://apps.mydomain.com/my-angular-app/index.html

The combined use of --deployUrl and --baseHref gives Angular apps the ability to do this.

However, this cannot be accomplished with only using the --baseHref option. The two outcomes:

  1. if index.html uses --baseHref equal to the cdn (ie. https://s3.cdn.com/my-angular-app/...)
    • assets are able to load
    • route throws an error and does not load the app (see error below)
  2. if index.html uses --baseHref equal to the "deployed" domain (ie. https://apps.mydomain.com/my-angular-app/)
    • assets cannot load because they are not uploaded to deployed domain

🔬 Minimal Reproduction

I created a minimum reproduction repo. It has a detailed README with setup and testing instructions. It also adds a little more context and clarity around the difference between a cdn url and the deployed url.

  • https://github.com/djhouseknecht/angular-deploy-url-repro

🔥 Exception or Error

Unhandled Navigation Error: SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'http://localhost:8080/fake-cdn/#/' cannot be created in a document with origin 'http://localhost:4200' and URL 'http://localhost:4200/thor/'.

Error is taken from the mini repo above

🌍 Your Environment


@angular-devkit/architect       0.1300.4
@angular-devkit/build-angular   13.0.4
@angular-devkit/core            13.0.4
@angular-devkit/schematics      13.0.4
@angular/cli                    13.0.4
@schematics/angular             13.0.4
rxjs                            7.4.0
typescript                      4.4.4

Anything else relevant? Extra relevant information in the minimum repo. The question/concern comes down to:

  • If the deployUrl is removed, will there be another way to accomplish a similar behavior of deployUrl without breaking the router?

djhouseknecht avatar May 03 '22 17:05 djhouseknecht

Duplicate of https://github.com/angular/angular/issues/43303

alan-agius4 avatar May 03 '22 17:05 alan-agius4

Addressing the Duplicate Issue

From the duplicate issue, it states that:

These are old techniques:

  1. Hash location strategy, as you mentioned this is supported for old server setup and no a days most users should have transitioned towards the path location strategy.
  2. CDN for assets only. This is also a relatively old technique which we don't recommand, we strongly recommand that the entire application is hosted on a CDN.

I would argue that albeity these are "old" techniques they are still very valid and have their place. For example:

  1. Not all Angular users will have access to the server to setup the server rewrite rules for the "modern" path strategy.
    • In our use case, we are using Route 53 & cloudflare to host a S3 bucket for our organizations web apps. These apps can be any framework that the individual teams choose. Given some federal restrictions and other organization audit rules, it is unfeasible to setup individual apps with specific routing rules.
  2. All our assets and index files are already (technically) hosted on a CDN. One just has Route53 attatching it to a custom domain.
    • the more traditional "cdn" is an S3 bucket with cloudflare, ie:
      • https://{cloudflare-hash}.cloudflare.com/{app-name}/{build-number}/...
    • the "deployed" cdn has Route53 attatched to it so customers can load something like this:
      • https://apps.{our-domain}.com/{app-name}/#/

Given our DevOps setups and legal restrictions, the above solution works perfectly.

Also, a couple advantages of this setup:

  • It requires no extra server configuration for development teams to deploy or manage their web applications (not to mention they can use whichever SPA framework they prefer).
  • We can deploy our apps' index.html file to any location on the "deployed" cdn and not have to worry about the server rules. For example:
    • We could have our prod version of the app deployed here:
      • https://apps.{our-domain}.com/{app-name}/#/
    • And then have a "beta" version deployed here for testing and beta customers to use:
      • https://apps.{our-domain}.com/{app-name}/beta/#/
    • We could do this with any url naming scheme we want because the assets are on the cloudflare CDN and the Angular app's hash routing does not care what the window.location.pathname is.
      • Footnote: we set <base href=""> to window.location.pathname to get this method to work.

I could go into more detail, but I am mostly trying to share that the Hash routing and ability to load assets from a separate CDN are huge advantages for us. The deployUrl made that possible and easy to configure.

My Current Solution

For anyone else coming here with the same question/issue, here is how we solved this for our angular apps (using the suggestion here):

app.module.ts

/* other imports */
import { HashLocationStrategy } from '@angular/common';
import { Injectable } from '@angular/core';

@Injectable()
export class CustomLocationStrategy extends HashLocationStrategy {
  get baseHref () {
    return this['_baseHref'];
  }

  /**
   * Override this to use `APP_BASE_HREF` + '/#/' + desired angular route
   */
  override prepareExternalUrl (internal: string): string {
    const url = this.joinWithHash(this.baseHref, internal);
    return url;
  }

  private joinWithHash (baseHref: string, hashRoute: string): string {
    let url = baseHref || '/';

    if (!url.endsWith('/')) {
      url += '/';
    }

    if (!hashRoute.startsWith('#')) {
      url += '#';
    }

    url += hashRoute;

    return url;
  }
}

@NgModule({
  /* other stuff */
  providers: [
    /* tell the router to use the "deployed" cdn and not the `<base href="...">` value (which is the asset cdn) */
    { provide: APP_BASE_HREF, useValue: window.location.origin + window.location.pathname },
    /* use our new strategy to ensure we build out the correct urls for `window.location.pushState` (so it doesn't error) */
    { provide: LocationStrategy, useClass: CustomLocationStrategy }
  ]
})
export class AppModule { }

Then when we build:

ng build --configuration production --baseHref={our-cdn-url}

Bug/Question

Looking over the code for hash_location_strategy.ts, I am wondering why it handles the APP_BASE_HREF so differently then the Path location_strategy?

// hash_location_strategy.ts
override prepareExternalUrl(internal: string): string {
  const url = joinWithSlash(this._baseHref, internal);
  return url.length > 0 ? ('#' + url) : url;
}

// location_strategy.ts
override prepareExternalUrl(internal: string): string {
  return joinWithSlash(this._baseHref, internal);
}

For example, given:

<!-- index.html -->
<head>
  <base href="https://cdn.com">
</head>

And:

// app.module.ts
  providers: [
    { provide: APP_BASE_HREF, useValue: 'https://example.com/' }
  ]

And an Angular route to /home, the two strategies behavior like:

  • PathLocationStrategy respects the APP_BASE_HREF, ignores the document's baseHref, and builds:
    • https://example.com/home
  • HashLocationStrategy always uses the document's baseHref and adds APP_BASE_HREF to the beginning of the Angular route:
    • https://cdn.com/#/https://example.com/home
    • desired would be the same as PathLocationStrategy, just with a # between the Angular route and APP_BASE_HREF like:
      • https://example.com/#/home

@alan-agius4, I don't know a ton about the router's inner-workings aside from the research I've done into this issue, but would it make sense to have the HashLocationStrategy build URLs the same as PathLocationStrategy does with respects to the APP_BASE_HREF?

I'm not sure if this would break current hash based routers, but it seems reasonable to have these two strategies behave the same in regards to the APP_BASE_HREF.

djhouseknecht avatar May 04 '22 20:05 djhouseknecht

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.