In this blog post we will go over how to add a simple sitemap.xml to your Angular App. For this tutorial I will be using Angular v11.0.4.
Create a sitemap.xml File
The first step to adding a sitemap.xml to your angular app is to create a sitemap.xml file. If you already have a sitemap file created, move onto the next step.
To create a sitemap, open up your favorite text editor and create an XML file using this format:
Each loc element should contain a unique page from your website. There are additional optional elements other than loc, but that is outside the scope of this blog post. If you are interested in understanding the sitemap.xml specifications, you can read more about sitemaps on Wikipedia. If you don’t want to create your XML sitemap by hand, I recommend using this online sitemap generator tool.
Adding the sitemap.xml to your Angular App
The next step is to add your sitemap.xml file to your app. You should copy and paste the file into the base of your Angular app in the /src folder. If you’re not sure if you are adding it to the right folder, the /src folder should contain your index.html, main.ts, and robots.txt files that make up the base of your Angular App.
Adding a Reference to your sitemap.xml File
In order to have your sitemap.xml file included in the distribution/production folder after you build your app, you will need to add the file to the assets section in your angular.json file. Your angular.json file should be located in your project’s root folder, right next to the src folder.
Here is what my angular.json file looks like with the sitemap.xml file included:
Test your sitemap.xml
Now that you’ve created your sitemap.xml and included the file in your build, let’s test our changes locally to make sure the sitemap.xml is available.
First, run your build command:
Next, serve your app so that we can navigate to the local instance:
Navigate to the localhost:[portnumber] that your application is being locally run on. For most projects the URL will be localhost:4200.
You should see your application up and running, now to test your sitemap.xml navigate to localhost:4200/sitemap.xml. You should see your sitemap.xml file that you created in the first step of this tutorial.
Deploy your Angular Application to Firebase
After you have confirmed that you can see your sitemap.xml file locally, it’s time to deploy your application to production and make sure that your sitemap.xml file is still working.
Run the following command to build and deploy your angular application to firebase:
ng build --prod | firebase deploy
Now navigate to your hosted application’s sitemap.xml, mine is hosted at https://www.brendansluke.com/sitemap.xml
You have now successfully added a sitemap.xml file to your Angular application and your Angular Application will be more SEO friendly.