
Amit Hariyale
Full Stack Web Developer, Gigawave
Full Stack Web Developer, Gigawave
Implementing proper SEO infrastructure can increase your Next.js application's visibility by up to 70%. This guide shows how to create both static and dynamic sitemaps along with optimized robots.txt files to maximize search engine crawling efficiency.
Key Features | Sitemap Generator |
---|---|
Static Routes | Predefined important pages |
Dynamic Routes | Automatically generated from app directory |
Custom Prioritization | Control SEO weight for each route |
Automatic Updates | Sitemap regenerates with new pages |
Automatically crawl your app
directory to find all routes:
1import { MetadataRoute } from "next";
2import fs from "fs";
3import path from "path";
4
5const APP_DIR = path.join(process.cwd(), "app");
6const BASE_URL = "https://yourdomain.com";
7const DEFAULT_CHANGE_FREQUENCY = "weekly";
8const DEFAULT_PRIORITY = 0.8;
9
10// Recursively find all page.tsx files
11function getAllPages(dir: string, baseRoute = ""): string[] {
12 let routes: string[] = [];
13 const files = fs.readdirSync(dir);
14
15 for (const file of files) {
16 const fullPath = path.join(dir, file);
17 const stat = fs.statSync(fullPath);
18
19 if (stat.isDirectory()) {
20 // Skip special Next.js folders
21 if (file.startsWith("_") || file === "api") continue;
22
23 routes = routes.concat(
24 getAllPages(fullPath, path.join(baseRoute, file))
25 );
26 } else if (file === "page.tsx") {
27 // Format the route
28 let route = baseRoute.replace(/\\/g, "/");
29 routes.push(route === "" ? "/" : `/${route}`);
30 }
31 }
32 return routes;
33}
34
35return function sitemap(): MetadataRoute.Sitemap {
36 const currentDate = new Date();
37 const routes = getAllPages(APP_DIR);
38
39 // Custom settings for important pages
40 const customSettings = {
41 "/": { changeFrequency: "daily", priority: 1 },
42 "/blog": { changeFrequency: "daily", priority: 0.9 },
43 "/pricing": { changeFrequency: "monthly", priority: 0.7 },
44 };
45
46 return routes.map((route) => {
47 const settings = customSettings[route] || {
48 changeFrequency: DEFAULT_CHANGE_FREQUENCY,
49 priority: DEFAULT_PRIORITY,
50 };
51
52 return {
53 url: `${BASE_URL}${route}`,
54 lastModified: currentDate,
55 ...settings
56 };
57 });
58}
The getAllPages
function recursively scans your app directory to find all page.tsx
files, converting them to valid routes.
Customize importance for critical pages:
1const customSettings = {
2 "/": { changeFrequency: "daily", priority: 1 }, // Highest priority
3 "/blog": { changeFrequency: "daily", priority: 0.9 }, // Important content
4 "/about": { changeFrequency: "monthly", priority: 0.5 } // Less critical
5};
For applications with frequently updated content:
1return async function sitemap() {
2 // Fetch dynamic routes from CMS
3 const blogs = await getBlogPosts();
4 const products = await getProducts();
5
6 return [
7 ...staticRoutes.map(route => ({ ...route })),
8 ...blogs.map(blog => ({
9 url: `https://yoursite.com/blog/${blog.slug}`,
10 lastModified: blog.updatedAt,
11 changeFrequency: 'weekly',
12 priority: 0.8,
13 })),
14 ...products.map(product => ({
15 url: `https://yoursite.com/products/${product.id}`,
16 lastModified: new Date(),
17 changeFrequency: 'monthly',
18 priority: 0.7,
19 })),
20 ];
21}
Complement your sitemap with a smart robots.txt file:
1import { MetadataRoute } from 'next';
2
3return function robots(): MetadataRoute.Robots {
4 return {
5 rules: {
6 userAgent: '*',
7 allow: '/',
8 disallow: ['/private/', '/admin/'],
9 },
10 sitemap: 'https://yourdomain.com/sitemap.xml',
11 host: 'https://yourdomain.com',
12 };
13}
1export const metadata = {
2 metadataBase: new URL('https://yourdomain.com'),
3 robots: {
4 index: true,
5 follow: true,
6 },
7};
Proper sitemap implementation is one of the highest ROI SEO activities you can perform. With this dynamic solution, your Next.js app will stay optimized as your content grows, helping search engines discover and prioritize your most important pages.
Remember: SEO is a marathon, not a sprint. Implement these techniques today to reap long-term ranking benefits!