Skip to content

Commit

Permalink
fix(router): support server-side-data-fetching when using a custom ba…
Browse files Browse the repository at this point in the history
…sehref (#997)
  • Loading branch information
leblancmeneses committed Apr 4, 2024
1 parent ff172a7 commit 433c50e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
51 changes: 51 additions & 0 deletions apps/docs-app/docs/features/deployment/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,54 @@ export default defineConfig({
],
});
```

## Deploying with a Custom URL Prefix

If you are deploying with a custom URL prefix, such as https://domain.com/`basehref`/ you must do these steps for [server-side-data-fetching](https://analogjs.org/docs/features/data-fetching/server-side-data-fetching), [html markup and assets](https://angular.io/api/common/APP_BASE_HREF), and [dynamic api routes](https://analogjs.org/docs/features/api/overview) to work correctly on the specified `basehref`.

1. Instruct Angular on how recognize and generate URLs. Create a new file `app.config.env.ts`.

```ts
import { ApplicationConfig } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';

export const envConfig: ApplicationConfig = {
providers: [{ provide: APP_BASE_HREF, useValue: '/basehref/' }],
};
```

2. Update the `app.config.ts` file to use the new file.

```ts
import { mergeApplicationConfig } from '@angular/core';
import { envConfig } from './app.config.env';

export const appConfig = mergeApplicationConfig(envConfig, {
....
});
```

3. In CI production build

```bash
# sets the base url for server-side data fetching
export VITE_ANALOG_PUBLIC_BASE_URL="https://domain.com/basehref"
# prefixes all assets and html with /basehref/
npx nx run appname:build:production --baseHref='/basehref/'
```

4. In production containers specify the env flag `NITRO_APP_BASE_URL`.

```bash
NITRO_APP_BASE_URL="/basehref/"
```

Given a `vite.config.ts` file similar to this:

```ts
plugins: [
analog({
apiPrefix: 'api',
```
Nitro prefixes all API routes with `/basehref/api`.
4 changes: 3 additions & 1 deletion packages/router/src/lib/route-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ export function toRouteConfig(routeMeta: RouteMeta | undefined): RouteConfig {
const segment =
parent?.url.map((segment) => segment.path).join('/') || '';
const url = new URL('', import.meta.env['VITE_ANALOG_PUBLIC_BASE_URL']);
url.pathname = `/api/_analog${routeConfig[ANALOG_META_KEY].endpoint}`;
url.pathname = `${
url.pathname.endsWith('/') ? url.pathname : url.pathname + '/'
}api/_analog${routeConfig[ANALOG_META_KEY].endpoint}`;
url.search = `${new URLSearchParams(queryParams).toString()}`;
url.hash = hash ?? '';

Expand Down

0 comments on commit 433c50e

Please sign in to comment.