{
  "id": "add-a-sitemap-and-robots",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "pt",
  "url": "/pt/playbooks/add-a-sitemap-and-robots",
  "title": "Prompt-to-PR: Adicionar um Sitemap e robots.txt",
  "description": "SOP para adicionar um sitemap XML dinâmico e robots.txt a um projeto Next.js ou Astro — corrigir lastmod, prioridade e regras de rastreamento para SEO em produção.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "Astro",
    "TypeScript"
  ],
  "tags": [
    "seo",
    "nextjs",
    "astro",
    "typescript"
  ],
  "difficulty": "easy",
  "updated": "2026-06-08",
  "markdown": "Sitemaps e `robots.txt` são as primeiras primitivas de SEO que um agente toca, e frequentemente estão errados — formato `lastmod` errado, diretiva `Sitemap:` ausente no robots, ou páginas bloqueadas incluídas inadvertidamente. Este manual acerta isso.\n\n## 1. Requisito\n\nProduza um sitemap XML cobrindo todas as rotas públicas (conteúdo estático + dinâmico do banco de dados) e um `robots.txt` que bloqueie caminhos admin/API e referencie o sitemap. Funciona tanto para Next.js App Router quanto Astro; escolha a abordagem correta para seu framework.\n\n## 2. Primeiro 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. Mudanças Esperadas nos Arquivos\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. Lista de Verificação\n\n- A URL base vem de uma variável de ambiente — não hardcoded como `http://localhost:3000`.\n- `lastModified` é um objeto `Date` do JavaScript (Next.js converte para ISO 8601) ou já uma string ISO válida — não `\"undefined\"` ou ausente.\n- `/admin`, `/api` e `/dashboard` estão na lista Disallow.\n- A diretiva `Sitemap:` em `robots.txt` usa uma URL absoluta.\n- Rotas dinâmicas (posts de blog) são incluídas via consulta ao banco de dados, não apenas rotas estáticas.\n- O sitemap não inclui páginas 404, de redirecionamento ou noindex.\n- Execute `bun run build` e depois `curl /sitemap.xml` retorna XML válido (verifique com `xmllint`).\n\n## 5. Comandos de Teste\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. Falhas Comuns\n\n- **`lastModified` é `\"undefined\"`** — campo `updatedAt` do post é nulo. Proteção: `lastModified: post.updatedAt ?? post.createdAt ?? new Date()`.\n- **Sitemap retorna 404** — `src/app/sitemap.ts` está faltando ou colocado fora do diretório `app`.\n- **Todas as rotas desabilitadas** — agente adiciona `Disallow: /` por engano. Confirme que apenas caminhos admin/API estão bloqueados.\n- **Diretiva `Sitemap:` tem URL relativa** — Google a ignora. Deve ser absoluta: `https://example.com/sitemap.xml`.\n- **Apenas sitemap estático** — agente hardcodea slugs de blog em vez de consultar o banco. Confirme que a função do sitemap é `async` e busca dados reais.\n\n## 7. Prompt de Correção\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. Descrição do 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```"
}