Prerender routes in Angular 18

xsip

Kerschbaumer Stefan

Posted on August 6, 2024

Prerender routes in Angular 18

So lets expect you wanna create a blog website using angular 18 and need to prerender your blog urls for SEO.

This is actually pretty easy.
To get started we need to generate a list of our URLs to prerender.
For that i wrote a simple script.
This script will connect to our backend and get a list of all Blog entry names and writes it to a file called "routes.txt".
We will later on use this file for prerendering

First of all create a backend returning all names of your blog entries. I did this by using NestJS and wont get into detail here.
The server returns as said before a string array.

To create a "routes.txt" file for all your blog entries use the following script:

Image description

The output will look like this:

Image description

Now edit your package.json build script to the following:
"build": "node routes-generator.js && ng build",

After that we need to configure our "angular.json" to use this file for pre-rendering and replace our enviroment file to connect to the server instead of using our proxy.conf.json while building.
This will look like this:

Image description

My environment files look like the following:

Image description

Now when running npm run build our sites will be pre-rendered and when serving without JS enabled in chrome everything should be rendered fine.

Lets have a look at our "dist" folder.

Image description

This looks pretty good!

Now lets serve our app.
First run npm i -g http-server, then navigate to dist/blog/server and run node server.mjs.

When we navigate to our route and disable Javascript everything is rendered perfectly fine.

Image description

I hope you learned something from this article and feel free to leave feedback.

Happy Coding!

💖 💪 🙅 🚩
xsip
Kerschbaumer Stefan

Posted on August 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Prerender routes in Angular 18
angular Prerender routes in Angular 18

August 6, 2024