Creating an Angular Application with Route Prerendering

Ole Ersoy
2 min readDec 11, 2023

--

Image by Sabine from Pixabay

Scenario

We want to prerender the routes / and /product:id .

Approach

Create a new Angular 17 (It has built in prerendering) application.

ng new --ssr ssr --style=scss && cd ssr

If you already have an Angular 17 app, add prerendering with ng add @angular/ssr .

Run the build with ng build . It will log.

Prerendered 1 static route.

And we look at dist/prerendered-routes.json we can see that it prerendered / .

Lets add the route product/:id . First generate the product component.

ng g c Product 

Within the ProductComponent grab the product/:id parameter.

export class ProductComponent {
private activatedRoute = inject(ActivatedRoute);
public id:string = this.activatedRoute.snapshot.params['id'];
}

Update the template so that it includes the id .

<p>product works!  Especially for the route {{id}}</p>

Then add the route in app.routes .

export const routes: Routes = [
{path: 'product/:id', component: ProductComponent}
];

Run the application ng serve -o and try out the path product/test . We should see that it renders the path.

Run ng build again. We see that it now prerenders 0 routes, but we are going to fix that.

Add the file routes.txt to the root of the project.

/
/product/Jeep
/product/Bronco

And update the prerender:true option within angular.json to.

"prerender": {
"routesFile": "routes.txt"
},

Run ng build again. We now see the message.

Prerendered 3 static routes.

And if we look in dist/prerendered-routes.json .

{
"routes": [
"/",
"/product/Bronco",
"/product/Jeep"
]
}

Voila! There are the routes being prerendered.

Demo

Clone this github repository.

git@github.com:fireflysemantics/ssr.git

--

--