How to Generate Sitemap For Static And Dynamic Pages with Next.js

2022-08-15

Why does the Sitemap matter?

If your website is SEO-friendly, you should definitely have a Sitemap and care about improving the perfomance of your website. Google uses a Sitemap to detect your pages, knowing the frequency of updating your content on that pages and their priority. Also, if you have a sitemap it's easy to send it to Google Search Console to detect new and updated pages. We will be using the next-sitemap package to create the Sitemap.

Generate a sitemap for static pages

We consider that you already know how to create the next.js app.

  1. Install next-sitemap using the following command:
    yarn add next-sitemap
  2. Add your domain to the .env config file
    NEXT_PUBLIC_DOMAIN_URL=https//yourwebsite.com/
  3. Create a new file called "next-sitemap.config.js" in the root folder of your app
    sitemap config in the next.js app
  4. Paste the following code to the next-sitemap.config.js file you just created
  5. /** @type {import('next-sitemap').IConfig} */
    const config = {
    	siteUrl: process.env.NEXT_PUBLIC_DOMAIN_URL,
    	exclude: ['/404', '/someAdminPages'],
    	generateRobotsTxt: true,
    	outDir: './out',
    	changefreq: 'monthly',
    	robotsTxtOptions: {
    		policies: [
    			{
    				userAgent: '*',
    				disallow: ['/404', '/someAdminPages'],
    			},
    			{ userAgent: '*', allow: '/' },
    		],
    	},
    };
    
    module.exports = config;
    • siteUrl - URL we added in 2 step
    • exclude - add the pages you don't need to be detected by Google Robots and available in the Google Search
    • generateRobotsTxt - we need it along with Sitemap to be SEO friendly
    • outDir - specify the folder Sitemap will created after the build your project
    • changefreq - tell Google Robots how often you are updating your content (“never”, “yearly”, “monthly”, “weekly”, “daily”, “hourly”, “always”)
    • robotsTxtOptions/disallow - we need to add paged you that don't need to be touched by Google Robots
  6. Add a Sitemap generation command to your package.json file into the build action
  7. Add Sitemap creating to the package.json config

    Now if we run

    yarn
    yarn build

    We will have our Sitemap in the "out" folder created for Static Pages. Probably you will have sitemap.xml and sitemap-n.xml files

    Sitemap.xml example

Generate a Sitemap for dynamic pages

To be able to generate a Sitemap for dynamic pages we will need to add "get static path" and "get static props" on the dynamic page [id]:

export async function getStaticProps({ params }) {
	let postId = params.id;
	const post = await getPostById(postId);

	return {
		props: {
			postItem: post || null,
		},
		revalidate: 10,
	};
}

export async function getStaticPaths() {
	const posts = await getPosts();
	let paths = [];
	posts.forEach((item) => {
		paths.push({
			params: {
				id: item.id,
			},
		});
	});


	return {
		paths,
		fallback: 'blocking',
	};
}

After adding this and building the project by the following command

yarn build

You will have your dynamic pages in the sitemap.xml file

Next.js Sitemap with dynamic pages

We hope, this will help you to improve your SEO and enjoy getting more visitors to your website!

Check our IT Consulting Services page to see which solutions could be useful for you.