Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(router): server-side-data-fetching when using basehref #997

Merged
merged 7 commits into from
Apr 4, 2024
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
Loading