`Location` does not support base href containing `origin` (only base hrefs with just the path are supported)

This issue has been created since 2022-11-22.

Which @angular/* package(s) are the source of the bug?

common, localize, router

Is this a regression?

No

Description

Routing gets broken if APP_BASE_HREF changed manually.

Regarding the docs, while deploying the bundles to CDN it needs to change the APP_BASE_HREF token to a URL where an app gonna be launched.

  provide: APP_BASE_HREF,
  useFactory: () => {
    const [, root, locale] = location.pathname.split('/');
    return `//${ location.host }/${ root }/${ locale }/`
  }

There is a simple implementation of it: https://github.com/constantant/cdn-i18n-routing-issue

Please provide a link to a minimal reproduction of the bug

https://konstantin.kharitonov.nl/cdn-i18n-routing-issue/en/

Please provide the exception or error you saw

core.mjs:9235 ERROR Error: Uncaught (in promise): Error: NG04002
Error: NG04002
    at j.noMatchError (router.mjs:3663:16)
    at router.mjs:3645:28
    at catchError.js:10:39
    at ne._error (OperatorSubscriber.js:23:21)
    at ne.error (Subscriber.js:40:18)
    at ne._error (Subscriber.js:64:30)
    at ne.error (Subscriber.js:40:18)
    at ne._error (Subscriber.js:64:30)
    at ne.error (Subscriber.js:40:18)
    at ne._error (Subscriber.js:64:30)
    at q (zone.js:1211:31)
    at q (zone.js:1165:17)
    at zone.js:1278:17
    at v.invokeTask (zone.js:406:31)
    at Object.onInvokeTask (core.mjs:26589:33)
    at v.invokeTask (zone.js:405:60)
    at M.runTask (zone.js:178:47)
    at _ (zone.js:585:35)
handleError @ core.mjs:9235
next @ core.mjs:27286
next @ Subscriber.js:91
_next @ Subscriber.js:60
next @ Subscriber.js:31
(anonymous) @ Subject.js:34
ne @ errorContext.js:19
next @ Subject.js:27
emit @ core.mjs:23077
(anonymous) @ core.mjs:26628
invoke @ zone.js:372
run @ zone.js:134
runOutsideAngular @ core.mjs:26501
onHandleError @ core.mjs:26628
handleError @ zone.js:376
runGuarded @ zone.js:147
i.microtaskDrainDone @ zone.js:1072
_ @ zone.js:592
Promise.then (async)
z @ zone.js:561
R @ zone.js:572
scheduleTask @ zone.js:396
onScheduleTask @ zone.js:283
scheduleTask @ zone.js:386
scheduleTask @ zone.js:221
scheduleMicroTask @ zone.js:241
ee @ zone.js:1265
q @ zone.js:1202
(anonymous) @ zone.js:1118
(anonymous) @ zone.js:1134
n @ jsonp chunk loading:77
(anonymous) @ 338.ac20b7bb511b4118.js:1
Show 18 more frames

Please provide the environment you discovered this bug in (run ng version)

_                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/
    

Angular CLI: 15.0.0
Node: 16.13.1
Package Manager: npm 8.14.0
OS: win32 x64

Angular: 15.0.0
... animations, cli, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1500.0
@angular-devkit/build-angular   15.0.0
@angular-devkit/core            15.0.0
@angular-devkit/schematics      15.0.0
@schematics/angular             15.0.0
rxjs                            7.5.7
typescript                      4.8.4

Anything else?

Notice that the minimal reproduction is building as a multilingual app with ng build --localize

The whole pipeline is available here: https://github.com/constantant/cdn-i18n-routing-issue/blob/master/.github/workflows/main.yml

atscott wrote this answer on 2022-11-22

This is working as expected. The application is misconfiguring APP_BASE_HREF and the <base> element. Your APP_BASE_HREF results in the router prepending //${ location.host }/${ root }/${ locale }/ to every route but it doesn't look like that's what you're intending. I think instead, you want to be setting APP_BASE_HREF to / and your base element would be configured to serve different assets from CDN.

This issue doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on StackOverflow using tag angular.

If you are wondering why we don't resolve support issues via the issue tracker, please check out this explanation.

constantant wrote this answer on 2022-11-22

@atscott

  1. The code is on https://d2nbgvwjuy9x2a.cloudfront.net/cdn-i18n-routing-issue/
  2. The app is on https://konstantin.kharitonov.nl/cdn-i18n-routing-issue/
  3. building with ng build --localize
  4. Each index.html has <base> as https://d2nbgvwjuy9x2a.cloudfront.net/cdn-i18n-routing-issue/{locale}/
  5. APP_BASE_HREF must be https://konstantin.kharitonov.nl/cdn-i18n-routing-issue/{locale}/

Which point is wrong here?

If all good it means that there is an issue, I guess

atscott wrote this answer on 2022-11-22

It looks like you want your APP_BASE_HREF to be /cdn-i18n-routing-issue/{locale}/. Does that resolve the issue?

constantant wrote this answer on 2022-11-22

@atscott
No, it will cause a security issue with the same result.

Unhandled Navigation Error: SecurityError: Failed to execute 'replaceState' on 'History': A history state object with URL 'https://d2nbgvwjuy9x2a.cloudfront.net/cdn-i18n-routing-issue/en/' cannot be created in a document with origin 'https://konstantin.kharitonov.nl' and URL 'https://konstantin.kharitonov.nl/cdn-i18n-routing-issue/en/'.
atscott wrote this answer on 2022-11-22

@constantant indeed, this is an issue. I'm surprised this isn't encountered more frequently. The Location is totally incapable of correctly processing a base href with an origin because it attempts to strip the base href from the path:

return this.normalize(this._locationStrategy.path(includeHash));

return Location.stripTrailingSlash(_stripBaseHref(this._baseHref, _stripIndexHtml(url)));

return baseHref && url.startsWith(baseHref) ? url.substring(baseHref.length) : url;

The path won't ever start with a base href containing the origin. Additionally, when the document's base element contains href, it seems like you can't call replaceState without a full URL. That is, simply calling window.history.replaceState({}, '', '/') will fail with the security exception you mentioned.

atscott wrote this answer on 2022-11-22

Note that you can work around this by forking Location and updating _stripBaseHref to handle your baseHref correctly (and then adding your fork to your providers for Location)

constantant wrote this answer on 2022-11-22

Thank you @atscott !
I've made it working now.

The main part is to strip origin for this._baseHref

function stripOrigin(baseHref: string): string {
  if (/^(https?:)?\/\//.test(baseHref)) {
    const [, pathname] = baseHref.split(/\/\/[^\/]+/);
    return pathname;
  }
  return baseHref;
}

https://github.com/constantant/cdn-i18n-routing-issue/blob/5b1af74895d4df445d553b6304629d2353b00ede/src/utils/fixed-location.ts#L40-L46

More Details About Repo
Owner Name angular
Repo Name angular
Full Name angular/angular
Language TypeScript
Created Date 2014-09-18
Updated Date 2022-12-01
Star Count 85220
Watcher Count 3042
Fork Count 22607
Issue Count 1316

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
TypeError:Cannot Call method "text" of null错误 0 2022-08-09 2022-11-14
Mechanism to open BottomSheet on top of a navigation bar 2 2022-04-09 2022-10-24
Note for Kali users: Please make sure you have installed --> apt-get install python3-dev apt-get install python-dev 6 2019-03-22 2022-11-06
New actions that preview the `lsp_definitions` in floating window? 1 2022-02-02 2022-10-04
Incompatible library version error with PG/RBENV? 0 2020-08-27 2022-08-29
Display status of cloud bucket access in the console for user profiles 0 2021-12-10 2022-11-21
loading and unloading the theme doesn't work correctly 4 2021-04-20 2022-10-16
Toc numbering is weird when using `defaults: numbered: true` 13 2021-06-24 2022-11-14
Upgrade to tensorflow2 0 2021-10-18 2022-10-21
请问如何加载一次模型预测多张图片?求助 1 2019-04-16 2021-11-30
求助:如何训练自己的模型 1 2018-12-17 2022-01-14
getssl needs to follow DNS validation CNAME records 6 2018-05-03 2022-11-02
Icon in menu bar not showing Mojave and Franz 5.6.1 0 2021-04-29 2021-12-31
how to fix that white line that appears between the statusbar 2 2020-08-20 2022-11-19
About pose files in training data. 0 2022-04-11 2022-11-23
[NBug] fatal: ambiguous argument 'HEAD': unknown revision or path ... 1 2022-03-23 2022-09-13
Cardinality Inference on cascading 4 2022-03-01 2022-10-14
“python_requires” should be set with “>=3”, as cloudtracker 2.1.5 is not compatible with all Python versions. 0 2022-03-07 2022-11-01
App crashes on Back press after adding remove series 3 2021-08-30 2022-11-08
IllegalStateException: Error: Value is null, api.setData 1 2021-12-09 2022-11-08
IllegalStateException 1 2021-10-01 2022-11-08
compile error: the trait bound `u64: ToUsize` is not satisfied on raspberry pi(armv7-unknown-linux-gnueabihf) 3 2021-07-11 2022-11-27
ReferenceError: [yenv] SETTING not found in the loaded environment 1 2020-12-04 2022-11-16
Absolute paths for files within tar archives 3 2020-11-14 2022-11-23
How to get the number of events emitted in the specific SC? 1 2022-04-27 2022-11-27
Can't evaluate if conditions properly with an undefined variable 7 2022-06-08 2022-11-29
使用了X-Tunnel,仍然无法翻过墙,研究了许久实在不知道错在何处,请指正 3 2022-11-11 2022-11-22
ATTACH Database documentation 3 2021-12-09 2022-09-27
Random Booster Draft Packs Selector Dialog cut off and not resizable 2 2021-12-18 2022-09-23
CompletionEntry cannot type word when SetText is called in widget.List 6 2022-04-02 2022-11-29
Build using Github Actions 23 2021-05-27 2022-10-17
[Feature]: useMatchedRoute() 6 2021-12-30 2022-11-13
Support of WebFlux 2 2021-11-24 2022-01-17
okta-hosted-login: nonce is a global but used for multiple sessions 2 2022-01-04 2022-11-15
Delete old non supported snapshots 2 2022-06-08 2022-11-24
Uncaught TypeError: can't access property "addEventListener", indexDialogPreviewModal is null 0 2022-06-10 2022-11-24
Release 1.6.1-alpha.1 as 1.6.1 2 2021-07-18 2022-10-08
Update Dockerfile handling to keep parser directives at the top 3 2021-08-04 2022-09-30
Preview window quits full-screen when changing crop options 3 2022-03-04 2022-09-26
Lazy loading of default SQSClient in order to make it work in quarkus /graalvm native 5 2021-07-16 2022-10-21
JWTUtil.createToken error 2 2021-09-20 2022-11-17
Invalid link for http://ping.rust-lang.org/ 0 2022-03-12 2022-11-10
Working Helm chart for registry backend 0 2018-09-23 2022-07-21
Recognize private methods outside the class 2 2022-01-27 2022-11-02
Text-based (non-PGS) Subtitles Display at Wrong Aspect Ratio on Videos with a "Display Aspect Ratio" Flag 6 2021-12-28 2022-10-16
tcnative.version property is not set in 4.1.68.Final version 3 2021-09-17 2022-11-23
Keyboard doesnt hide when clicked on menu buttons of download screen and choose language 9 2021-12-06 2022-10-29
使用searchNodes功能后,nodeCheck方法返回节点无parent()方法 3 2019-07-13 2022-11-13
refactor: remove unused dependencies 2 2021-10-31 2022-09-25
Website suggestion: https://bookmarkos.com 0 2018-07-18 2022-10-12