I have an Angular project, and I'm attaching the app.routes.ts
file. When I test it with ng serve
, the app seems to work perfectly, but when I try to build it I always get this error:
✘ [ERROR] The 'esperimento/:id' route uses prerendering and includes parameters, but 'getPrerenderParams' is missing. Please define the 'getPrerenderParams' function for this route in your server routing configuration or specify a different 'renderMode'.
I can't find a solution. Can anyone help me?
// app/app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { ExperimentComponent } from './pages/experiment/experiment.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'esperimento/:id', component: ExperimentComponent }
];
As mentioned in the documentation.
For each route with RenderMode.Prerender, you can specify a getPrerenderParams function. This function lets you control which specific parameters produce separate prerendered documents.
So specify an API call that gets all the IDs that you want to prerender.
// app.routes.server.ts
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: 'esperimento/:id',
renderMode: RenderMode.Prerender,
async getPrerenderParams() {
const dataService = inject(PostService);
const ids = await dataService.getIds(); // Assuming this returns ['1', '2', '3']
return ids.map(id => ({ id })); // Transforms IDs into an array of objects for prerendering
// This will prerender the paths: `/esperimento/1`, `/esperimento/2` and `/esperimento/3`
},
},
];
If you do not need Prerendering
, just configure the route as a client or server only route (Without prerendering).
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'esperimento/:id', component: ExperimentComponent, renderMode: RenderMode.Server, }, // render on server and client
// { path: 'esperimento/:id', component: ExperimentComponent, renderMode: RenderMode.Client, } // render on client only
];
Another approach, is to configure the routes you want to prerender.
Prerendering parameterized routes
/products/1
/products/555
Maybe you have discoverRoutes
enabled which is causing this route to prerender.
{
"projects": {
"my-app": {
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"prerender": {
"discoverRoutes": false // <- this line might be the problem.
}
}
}
}
}
}
}