basehref vs APP_BASE_HREF in Angular
base-href (CLI flag or <base> tag) sets the base URL for fetching assets (JS, CSS, images) and browser routing, affecting the physical path. {Link: APP_BASE_HREF https://angular.dev/api/common/APP_BASE_HREF} is an Angular InjectionToken used solely by the router to manage URL prefixing within the application, typically for dynamic pathing or subfolder deployment without changing the index.html.
Key Differences
base-href(CLI--base-hrefor<base href="...">):- Scope: Browser/Network level.
- Purpose: Tells the browser where to find
main.js, styles, and assets. - Setting: Configured at build time (
ng build --base-href /my-app/).
APP_BASE_HREF(Angular Provider):- Scope: Application/Router level.
- Purpose: Tells the Angular Router to add a prefix to routes (e.g.,
/{lang}/home). - Setting: Configured in
AppModuleorapp.config.ts.
When to Use Which
- Use
base-hrefwhen deploying your app to a subfolder (e.g.,example.com/subfolder/). - Use
APP_BASE_HREFfor dynamic base pathing, such as setting a language prefix (/en/,/fr/) to all routes without changing how assets are loaded. - If both are set,
APP_BASE_HREFoverrides the route calculation part, butbase-hrefstill dictates asset loading.
How to use:
base-href
- add in angular.json file in projects > projectName > build > configurations > production
"baseHref": "/your-app-path/",
- add the
base hrefcan be set in an Angular CLI command using the--base-hrefflag withng buildorng serve. - For building your application (e.g., for production deployment):
ng build --base-href=/your-app-path/
- For serving your application locally (development):
ng serve --base-href=/your-app-path/
APP_BASE_HREF
- add in app.config.ts providers
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withHashLocation } from '@angular/router';
import { routes } from './app.routes';
import { APP_BASE_HREF } from '@angular/common';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
{ provide: APP_BASE_HREF, useValue: '/your-app-path/' }
]
};