How to Create a Robots.txt File in Astro

How to Create a Robots.txt File in Astro

Learn how to architect, automate, and deploy enterprise-grade robots.txt files in Astro across static, SSR, edge, and multi-tenant environments.

In enterprise web architectures, search engine optimization (SEO) and web crawler management are frequently treated as operational afterthoughts. Yet, a misconfigured robots.txt file can decimate search engine indexation, leak internal staging endpoints to public search engines, or expose infrastructure to unthrottled scraping by Generative AI crawlers.

As organizations transition from monolithic web platforms to lightweight, content-focused frameworks like Astro, standardizing the deployment of the Robots Exclusion Protocol (RFC 9309) requires careful architectural consideration. Astro’s flexible output targets—ranging from static site generation (SSG) to server-side rendering (SSR) at the edge—demand a strategy that goes beyond placing a static file in the /public directory.

This guide explores the engineering patterns required to build robust, environment-aware, and programmatic robots.txt pipelines in Astro.


The Limitations of Static File Handlers in Enterprise Architectures

The naive approach to managing crawler instructions in Astro is dropping a static robots.txt file into the public/ folder:

# public/robots.txt (Anti-pattern for complex apps)
User-agent: *
Allow: /
Sitemap: https://example.com/sitemap-index.xml

While sufficient for static personal blogs, this approach introduces architectural vulnerabilities in enterprise applications:

  1. Environment Contamination: Staging, preview, and ephemeral CI/CD environments pull static assets verbatim. If a staging build is publicly accessible, standard static files allow search engines to index non-production environments, causing duplicate content penalties or security leaks.
  2. Hardcoded Hostnames: Enterprise sites often feature multi-region domains, dynamic subdomains, or complex internationalization (i18n) routing strategies where the sitemap URL cannot be known at compile-time.
  3. Dynamic Disallow Rules: Modern applications feature dynamic, user-generated, or feature-flagged routes (e.g., /account/*, /beta/*, dynamic API endpoints) that static text files cannot adaptively hide based on application state or deployment flags.
  4. AI/LLM Bot Mitigation Strategy: The modern crawler landscape includes high-frequency AI scraping agents (e.g., GPTBot, ClaudeBot, CCBot). Enterprises require configurable disallow rules that can be updated globally or dynamically driven by microservice configuration endpoints.

To solve these constraints, Astro engineers must leverage Dynamic Endpoint Endpoints (.ts), Environment Variable Injection, and custom Astro Integrations.


Architectural Overview: Crawl Control at the Edge

Before diving into code implementations, consider how an enterprise request pipeline evaluates crawler directives.

  +-------------------------------------------------------------------------+
  |                           Incoming Request                              |
  |                    GET /robots.txt (User-Agent)                         |
  +-------------------------------------------------------------------------+
                                       |
                                       v
  +-------------------------------------------------------------------------+
  |                           Edge / CDN Layer                              |
  |         (Cloudflare Workers / Vercel Edge / Fastly Compute)             |
  +-------------------------------------------------------------------------+
                                       |
                   +-------------------+-------------------+
                   |                                       |
                   v                                       v
      [Environment: Production]                 [Environment: Non-Prod]
                   |                                       |
                   v                                       v
  +---------------------------------+     +---------------------------------+
  | Execute Astro Dynamic Endpoint  |     | Return Strict Disallow Directive|
  |   - Parse site config           |     |                                 |
  |   - Inject localized sitemaps   |     |  User-agent: *                  |
  |   - Apply AI Scraper Policy     |     |  Disallow: /                    |
  |   - Return cached text/plain    |     +---------------------------------+
  +---------------------------------+
                   |
                   v
  +---------------------------------+
  | Cache Directive: s-maxage=86400 |
  +---------------------------------+

Pattern 1: Dynamic Static Site Generation (SSG) Endpoint

If your Astro application is configured for SSG (output: 'static', the default target), you should avoid the static public/robots.txt file in favor of an Astro API Endpoint written in TypeScript (src/pages/robots.txt.ts).

Astro evaluates .ts files inside src/pages/ as build-time dynamic routes. During astro build, Astro executes the endpoint’s GET handler once and compiles the resulting plain-text output into the final distribution folder (dist/robots.txt).

Production TypeScript Endpoint Implementation

Create src/pages/robots.txt.ts:

import type { APIRoute } from 'astro';

// Environment configurations
const IS_PRODUCTION = import.meta.env.PROD_ENV === 'true' || import.meta.env.NODE_ENV === 'production';

// Common AI scrapers to disallow for corporate IP protection
const BLOCKED_AI_BOTS = [
  'GPTBot',
  'ChatGPT-User',
  'CCBot',
  'anthropic-ai',
  'ClaudeBot',
  'Omgilibot',
  'FacebookBot',
];

/**
 * Generates environment-aware robots.txt content
 */
function generateRobotsTxt(site: URL): string {
  // Strict disallow for non-production environments
  if (!IS_PRODUCTION) {
    return `# Staging/Preview Environment - Block All Crawling
User-agent: *
Disallow: /
`;
  }

  const sitemapURL = new URL('sitemap-index.xml', site).href;

  const aiBotRules = BLOCKED_AI_BOTS.map(
    (bot) => `User-agent: ${bot}\nDisallow: /`
  ).join('\n\n');

  return `# Production Robots Directive
User-agent: *
Allow: /
Disallow: /api/
Disallow: /internal/
Disallow: /_astro/
Disallow: /drafts/

# Block AI and LLM Scrapers
${aiBotRules}

# Sitemap Index
Sitemap: ${sitemapURL}
`;
}

export const GET: APIRoute = ({ site }) => {
  // Fallback if site is not defined in astro.config.mjs
  const fallbackSite = new URL('https://www.example.com');
  const targetSite = site ?? fallbackSite;

  const content = generateRobotsTxt(targetSite);

  return new Response(content, {
    status: 200,
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      // Cache directives for CDN optimization
      'Cache-Control': 'public, max-age=3600, s-maxage=86400',
    },
  });
};

Configuration Requirements

For site to be correctly passed into the APIRoute context, ensure your astro.config.mjs defines your canonical base URL:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';

export default defineConfig({
  site: process.env.SITE_URL || 'https://www.example.com',
  integrations: [sitemap()],
  output: 'static',
});

Pattern 2: On-Demand SSR & Edge-Driven Crawl Directives

When deploying Astro as an SSR application using output: 'server' or output: 'hybrid' with adapters (such as @astrojs/cloudflare, @astrojs/node, or @astrojs/vercel), robots.txt can be rendered dynamically per HTTP request.

SSR configuration enables domain-based policy evaluation, runtime environment inspection (e.g., reading request headers to verify domain tenants), and header manipulation directly at edge runtime.

Enterprise SSR Implementation (src/pages/robots.txt.ts)

import type { APIRoute } from 'astro';

// Export prerender = false to force SSR execution on hybrid builds
export const prerender = false;

interface EnvironmentRules {
  disallowedPaths: string[];
  allowIndexing: boolean;
}

/**
 * Determines indexing parameters based on runtime environment variables
 * and request host headers.
 */
function resolveEnvironmentRules(request: Request): EnvironmentRules {
  const host = request.headers.get('host') || '';
  const runtimeEnv = process.env.DEPLOYMENT_ENV || process.env.NODE_ENV;

  // Protect internal infrastructure, admin domains, or preview deployments
  const isInternalDomain = host.includes('internal') || host.includes('staging') || host.includes('.vercel.app');
  const isProduction = runtimeEnv === 'production' && !isInternalDomain;

  if (!isProduction) {
    return {
      allowIndexing: false,
      disallowedPaths: ['/'],
    };
  }

  return {
    allowIndexing: true,
    disallowedPaths: [
      '/api/',
      '/auth/',
      '/checkout/',
      '/search',
      '/*?*query=', // Block aggressive canonical parameter crawling
    ],
  };
}

export const GET: APIRoute = ({ request, site }) => {
  const { allowIndexing, disallowedPaths } = resolveEnvironmentRules(request);
  const host = request.headers.get('host');
  const protocol = request.headers.get('x-forwarded-proto') || 'https';
  
  // Construct dynamic canonical origin based on incoming Edge request headers
  const origin = host ? `${protocol}://${host}` : (site?.origin || 'https://www.example.com');

  let body = '';

  if (!allowIndexing) {
    body = `# Disallow indexing on non-production domains\nUser-agent: *\nDisallow: /\n`;
  } else {
    const disallowDirectives = disallowedPaths
      .map((path) => `Disallow: ${path}`)
      .join('\n');

    body = [
      'User-agent: *',
      'Allow: /',
      disallowDirectives,
      '',
      `# Canonical Sitemap Location`,
      `Sitemap: ${origin}/sitemap-index.xml`,
    ].join('\n');
  }

  return new Response(body, {
    status: 200,
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      // Ensure shared proxies and edge CDNs revalidate dynamic responses
      'Cache-Control': 'public, max-age=0, s-maxage=86400, must-revalidate',
      'X-Robots-Tag': allowIndexing ? 'all' : 'noindex, nofollow',
    },
  });
};

Pattern 3: Automated Integration via Custom Astro Plugin

For multi-repository enterprises managing dozens of Astro micro-sites, duplicating src/pages/robots.txt.ts across every service creates maintenance overhead.

By implementing a Custom Astro Integration, you can encapsulate robots.txt generation into a reusable npm module that hooks into Astro’s build engine lifecycle.

Designing the Custom Integration Plugin

Here is how to construct a custom Astro integration using the astro:config:done and astro:build:done lifecycle hooks.

Step 1: Write the Integration Module (integration/astro-robots-telemetry.ts)

import type { AstroIntegration } from 'astro';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

export interface RobotsIntegrationOptions {
  policy: Array<{
    userAgent: string;
    allow?: string[];
    disallow?: string[];
    crawlDelay?: number;
  }>;
  sitemap?: string | boolean;
  protectNonProd?: boolean;
}

export default function robotsIntegration(options: RobotsIntegrationOptions): AstroIntegration {
  let resolvedSite: string | undefined;
  let outDirUrl: URL;

  return {
    name: '@enterprise/astro-robots-manager',
    hooks: {
      'astro:config:done': ({ config }) => {
        resolvedSite = config.site;
        outDirUrl = config.outDir;
      },
      'astro:build:done': async ({ logger }) => {
        logger.info('Generating dynamic enterprise robots.txt...');

        const isProd = process.env.NODE_ENV === 'production' && process.env.VERCEL_ENV !== 'preview';

        let content = '';

        if (options.protectNonProd && !isProd) {
          content = `# Environment restricted via Build Integration\nUser-agent: *\nDisallow: /\n`;
        } else {
          const rules: string[] = [];

          for (const block of options.policy) {
            rules.push(`User-agent: ${block.userAgent}`);
            if (block.crawlDelay) {
              rules.push(`Crawl-delay: ${block.crawlDelay}`);
            }
            if (block.allow) {
              block.allow.forEach((p) => rules.push(`Allow: ${p}`));
            }
            if (block.disallow) {
              block.disallow.forEach((p) => rules.push(`Disallow: ${p}`));
            }
            rules.push(''); // Blank line separator
          }

          // Compute Sitemap configuration
          if (options.sitemap !== false) {
            const sitemapPath = typeof options.sitemap === 'string' 
              ? options.sitemap 
              : 'sitemap-index.xml';

            const base = resolvedSite ? resolvedSite.replace(/\/$/, '') : '';
            if (base) {
              rules.push(`Sitemap: ${base}/${sitemapPath}`);
            }
          }

          content = rules.join('\n');
        }

        // Write file directly to dist output directory
        const outDirPath = fileURLToPath(outDirUrl);
        const robotsPath = path.join(outDirPath, 'robots.txt');

        try {
          await fs.writeFile(robotsPath, content, 'utf-8');
          logger.info(`Successfully written robots.txt to ${robotsPath}`);
        } catch (err) {
          logger.error(`Failed to write robots.txt: ${String(err)}`);
          throw err;
        }
      },
    },
  };
}

Step 2: Register in astro.config.mjs

Now pass the integration configuration cleanly into the enterprise configuration file:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
import enterpriseRobots from './integration/astro-robots-telemetry';

export default defineConfig({
  site: 'https://www.enterprise-app.com',
  integrations: [
    sitemap(),
    enterpriseRobots({
      protectNonProd: true,
      policy: [
        {
          userAgent: '*',
          allow: ['/'],
          disallow: ['/admin/', '/private/', '/api/'],
        },
        {
          userAgent: 'GPTBot',
          disallow: ['/'],
        },
      ],
    }),
  ],
});

Edge Protection: HTTP Response Headers vs. Robots.txt

A common enterprise vulnerability occurs when software teams rely exclusively on robots.txt to hide sensitive environments.

According to RFC 9309, robots.txt is an advisory standard. Malicious crawlers, indexers, and automated vulnerability scanners frequently ignore disallow directives. Furthermore, if a public page outside your application links to your staging domain, search engines may still index the URL itself (without parsing its body content) even if robots.txt disallows crawling.

To ensure complete indexation protection, combine your robots.txt pipeline with the X-Robots-Tag HTTP header emitted via middleware.

Implementing Defense-in-Depth Middleware (src/middleware.ts)

import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware(async (context, next) => {
  const response = await next();
  const host = context.request.headers.get('host') || '';
  const isProductionDomain = host === 'www.enterprise-app.com' || host === 'enterprise-app.com';

  // Inject strict HTTP indexation headers for non-production environments
  if (!isProductionDomain) {
    response.headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive, nosnippet');
  }

  return response;
});

Managing Multi-Tenant & i18n Robots Configurations

Enterprise applications supporting internationalization (i18n) via distinct path prefixes (e.g., /en/, /fr/, /ja/) or explicit subdomains require dynamic sitemap discovery within robots.txt.

Astro’s native i18n configuration works alongside robots.txt endpoints to expose localized index locations dynamically:

// src/pages/robots.txt.ts
import type { APIRoute } from 'astro';

const SUPPORTED_LOCALES = ['en', 'fr', 'de', 'ja', 'es'];

export const GET: APIRoute = ({ site }) => {
  const domain = site ? site.origin : 'https://www.example.com';

  // Generate localized sitemaps automatically based on internationalization schemas
  const localizedSitemaps = SUPPORTED_LOCALES.map(
    (locale) => `Sitemap: ${domain}/${locale}/sitemap.xml`
  ).join('\n');

  const content = `User-agent: *
Allow: /
Disallow: /api/

# Primary Index
Sitemap: ${domain}/sitemap-index.xml

# Regional Sitemaps
${localizedSitemaps}
`;

  return new Response(content, {
    headers: { 'Content-Type': 'text/plain; charset=utf-8' },
  });
};

Verification & Automated CI/CD Testing

To prevent regression bugs in production releases (such as accidentally shipping Disallow: / to production), integrate automated verification assertions into your continuous integration (CI) pipeline.

Unit Testing Endpoint Output via Vitest

// tests/robots.test.ts
import { describe, it, expect, vi } from 'vitest';
import { GET } from '../src/pages/robots.txt';

describe('Robots.txt Pipeline Generation', () => {
  it('should allow crawling in production environment', async () => {
    vi.stubEnv('NODE_ENV', 'production');
    vi.stubEnv('PROD_ENV', 'true');

    const context = {
      site: new URL('https://www.example.com'),
      request: new Request('https://www.example.com/robots.txt'),
    };

    // @ts-ignore - Partial Mock of APIContext
    const response = await GET(context);
    const text = await response.text();

    expect(response.status).toBe(200);
    expect(text).toContain('Allow: /');
    expect(text).toContain('Sitemap: https://www.example.com/sitemap-index.xml');
    expect(text).not.toContain('Disallow: /');
  });

  it('should enforce total disallow on staging domains', async () => {
    vi.stubEnv('NODE_ENV', 'development');
    vi.stubEnv('PROD_ENV', 'false');

    const context = {
      site: new URL('https://staging.example.com'),
      request: new Request('https://staging.example.com/robots.txt'),
    };

    // @ts-ignore
    const response = await GET(context);
    const text = await response.text();

    expect(text).toContain('Disallow: /');
  });
});

Production Readiness Checklist

Before deploying your Astro application to production, run your infrastructure through this validation framework:

Verification Target Expected Configuration Method
Static File Check Ensure public/robots.txt does not exist if using .ts dynamic endpoints to prevent asset collisions. File System Audit
Header Verification Content-Type must be explicitly defined as text/plain; charset=utf-8. HTTP Header Inspection
Sitemap Coupling Sitemap: targets absolute, fully qualified HTTPS URLs (never relative paths like /sitemap.xml). Protocol Standard Validation
Environment Isolation Non-production domains return Disallow: / AND include X-Robots-Tag: noindex, nofollow headers. Edge Middleware Test
AI Bot Strategy Explicit rules are active for high-volume scrapers (GPTBot, CCBot) per enterprise data compliance policies. User-Agent Header Emulation
Cache Control Edge CDN caches responses with an appropriate s-maxage (e.g., 86400s) to reduce origin hits while allowing invalidation. CDN Cache Strategy Audit

Conclusion

Managing robots.txt in enterprise Astro applications requires moving beyond legacy static text files. By leveraging Astro TypeScript API Endpoints, constructing Custom Build Integrations, and executing Edge Middleware Protection, frontend platform teams can establish resilient, zero-trust crawler management architectures across complex multi-environment infrastructure.