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:
The output will look like this:
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:
My environment files look like the following:
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.
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.
I hope you learned something from this article and feel free to leave feedback.
Happy Coding!
Top comments (2)
Why installing http-server if you don't use it?
i mixed something here. That's my fault. thanks for pointing it out!
It's not needed at all.