{
  "id": "add-a-sitemap-and-robots",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "fr",
  "url": "/fr/playbooks/add-a-sitemap-and-robots",
  "title": "Prompt-to-PR : Ajouter un sitemap et un robots.txt",
  "description": "Procédure standard pour ajouter un sitemap XML dynamique et un robots.txt à un projet Next.js ou Astro — format lastmod correct, priorité et règles d'exploration pour le SEO en production.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "Astro",
    "TypeScript"
  ],
  "tags": [
    "seo",
    "nextjs",
    "astro",
    "typescript"
  ],
  "difficulty": "easy",
  "updated": "2026-06-08",
  "markdown": "Les sitemaps et `robots.txt` sont les premières primitives SEO qu'un agent manipule, et elles sont souvent erronées — mauvais format `lastmod`, directive `Sitemap:` manquante dans robots, ou pages bloquées incluses par inadvertance. Ce guide les corrige.\n\n## 1. Exigence\n\nProduire un sitemap XML couvrant toutes les routes publiques (contenu statique + dynamique depuis la base de données) et un `robots.txt` qui bloque les chemins admin/API et référence le sitemap. Fonctionne à la fois avec Next.js App Router et Astro ; choisissez l'approche correcte pour votre framework.\n\n## 2. Premier prompt\n\n```txt title=\"First Prompt\"\nAdd a sitemap.xml and robots.txt to this project. Use the correct approach\nfor the framework detected below.\n\n### If Next.js 14+:\n1. Create `src/app/sitemap.ts` using the Next.js `MetadataRoute.Sitemap`\n   return type. Include:\n   - All static routes: /, /pricing, /blog, /about (hardcoded is fine).\n   - All dynamic blog posts: fetch slugs from the DB using the existing\n     query helper, return lastModified from the post's updatedAt field.\n   - Use `process.env.NEXT_PUBLIC_APP_URL` as the base URL.\n   - Correct W3C datetime format for lastModified (ISO 8601).\n2. Create `src/app/robots.ts` using MetadataRoute.Robots.\n   - Allow: all routes.\n   - Disallow: /admin, /api, /dashboard.\n   - Add `sitemap: process.env.NEXT_PUBLIC_APP_URL + \"/sitemap.xml\"`.\n\n### If Astro:\n1. Add `@astrojs/sitemap` integration. In astro.config.ts, add\n   `sitemap({ filter: (page) => !page.includes(\"/admin\") })` and set\n   `site: process.env.SITE_URL`.\n2. Create `public/robots.txt`:\n   User-agent: *\n   Disallow: /admin\n   Disallow: /api\n   Sitemap: <SITE_URL>/sitemap-index.xml\n\nDo not create a custom sitemap endpoint if the integration handles it.\nDo not block / or any public content pages.\n```\n\n## 3. Modifications de fichiers attendues\n\n```txt\n### Next.js\nsrc/app/sitemap.ts             (new — dynamic MetadataRoute.Sitemap)\nsrc/app/robots.ts              (new — MetadataRoute.Robots)\n\n### Astro\nastro.config.ts                (add sitemap integration + filter)\npublic/robots.txt              (new)\n.env.example                   (SITE_URL added if missing)\n```\n\n## 4. Liste de vérification\n\n- L'URL de base provient d'une variable d'environnement — pas codée en dur comme `http://localhost:3000`.\n- `lastModified` est un objet JavaScript `Date` (Next.js le convertit en ISO 8601) ou déjà une chaîne ISO valide — pas `\"undefined\"` ou absent.\n- `/admin`, `/api` et `/dashboard` sont dans la liste Disallow.\n- La directive `Sitemap:` dans `robots.txt` utilise une URL absolue.\n- Les routes dynamiques (articles de blog) sont incluses via une requête DB, pas seulement les routes statiques.\n- Le sitemap n'inclut pas les pages 404, de redirection ou noindex.\n- `bun run build` puis `curl /sitemap.xml` retourne un XML valide (vérifier avec `xmllint`).\n\n## 5. Commandes de test\n\n```bash\nbun run build && bun run start\n# or for Astro:\nbun run build && bun run preview\n\n# Validate sitemap XML\ncurl -s http://localhost:3000/sitemap.xml | xmllint --format - | head -40\n\n# Confirm robots.txt\ncurl http://localhost:3000/robots.txt\n\n# Confirm admin is disallowed and sitemap directive is present\ngrep -E \"Disallow|Sitemap\" <(curl -s http://localhost:3000/robots.txt)\n\n# Google Rich Results / URL Inspection simulation\ncurl -A \"Googlebot\" http://localhost:3000/sitemap.xml -I\n```\n\n## 6. Échecs courants\n\n- **`lastModified` est `\"undefined\"`** — le champ `updatedAt` du post est nul. Sécurisation : `lastModified: post.updatedAt ?? post.createdAt ?? new Date()`.\n- **Le sitemap retourne 404** — `src/app/sitemap.ts` est manquant ou placé en dehors du répertoire `app`.\n- **Toutes les routes interdites** — l'agent ajoute `Disallow: /` par erreur. Confirmez que seuls les chemins admin/API sont bloqués.\n- **La directive `Sitemap:` a une URL relative** — Google l'ignore. Doit être absolue : `https://example.com/sitemap.xml`.\n- **Sitemap statique uniquement** — l'agent code en dur les slugs de blog au lieu d'interroger la DB. Confirmez que la fonction sitemap est `async` et récupère des données réelles.\n\n## 7. Prompt de correction\n\n```txt title=\"Fix Prompt\"\nThe sitemap.xml at /sitemap.xml includes every blog post with\nlastModified \"undefined\" (rendered as the string).\n\nFix in src/app/sitemap.ts:\n  const posts = await getBlogPosts();\n  return posts.map((post) => ({\n    url: `${BASE_URL}/blog/${post.slug}`,\n    lastModified: post.updatedAt ?? post.createdAt ?? new Date(),\n    changeFrequency: \"weekly\",\n    priority: 0.8,\n  }));\n\nEnsure getBlogPosts() returns rows that include updatedAt and createdAt.\n```\n\n## 8. Description de la PR\n\n```md title=\"PR description\"\n## SEO: Add dynamic sitemap.xml and robots.txt\n\n**Next.js**: `src/app/sitemap.ts` + `src/app/robots.ts` using built-in\n`MetadataRoute` types. Sitemap includes static routes + all published blog\nposts with correct `lastModified` timestamps from the DB.\n\n**robots.txt** disallows `/admin`, `/api`, `/dashboard`; includes absolute\n`Sitemap:` directive pointing to the generated `/sitemap.xml`.\n\nBase URL read from `NEXT_PUBLIC_APP_URL` — no localhost URLs in production.\n```"
}