So, recently I have been building an eshop for a client and one of the usual SEO improvements you can do is to generate a sitemap so that Google search does its magic. So, I figured ok lets try to find how to do that (being my first time doing that using NextJS and NX).
How hard could it be?
Hmm, well turns out not that much but if you search for the combination of NextJS, NX and Sitemap you won't find much. Hence, I figured to create a small guide, perhaps helping someone.
Step 1 - Install Next Sitemap
yarn add -D next-sitemap
Step 2 - Create a next-sitemap.js config
Now this goes into the app you are going to deploy.
# apps/eshop/next-sitemap.js
module.exports = {
siteUrl: <your-side-url>,
generateRobotsTxt: true,
sitemapSize: 7000,
changefreq: 'daily',
priority: 0.7,
};
Step 3 - Update workspace.json to create a postbuild script
#workspace.json
...
"eshop": {
"root": "apps/eshop",
"sourceRoot": "apps/eshop",
"projectType": "application",
"targets": {
"build": {
"executor": "@nrwl/next:build",
"outputs": ["{options.outputPath}"],
"options": {
"root": "apps/eshop",
"outputPath": "dist/apps/eshop"
},
"configurations": {
"production": {}
}
},
# important part below
"postbuild": {
"executor": "@nrwl/workspace:run-commands",
"options": {
"commands": [
{
"command": "next-sitemap --config apps/eshop/next-sitemap.js"
}
]
}
},
...
Now we have access to the following command
nx run eshop:postbuild
Step 4 - Make sure it works
Next sitemap is looking for a .next
directory to be present and able to work. By default if you run nx run eshop:build --prod
it will create a dist/apps/eshop
folder
For testing purposes (or if you deploying to Vercel for example) run the following command
nx build eshop --prod --outputPath=.
It will generate the output in the root folder
Fair warning this will polute your dir so be sure to not commit unnecessary files
Next, run the sitemap generator
nx run eshop:postbuild
You should now have a sitemap generated under public
folder.
Step 5 - Use this command during deployments
Usually you want to generate a new sitemap on each deployment so combining above two commands should do the trick
# example build command used on Vercel
npx nx build eshop --prod --outputPath=. && nx run eshop:postbuild
Thats it folks - hope that was helpful.