Next.js Discord

Discord Forum

dynamic robots.txt depending on environment

Unanswered
Devon Rex posted this in #help-forum
Open in Discord
Devon RexOP
Hello,

I am trying to have a different robots.txt depending of the environment (allow: / on production, otherwise disallow: /).

However, I did try with the robots.ts file or robots.txt/route.ts to generate it based on serverRuntimeConfig but it seems to be statically generated.

I am using app router

Here's my code
import getConfig from 'next/config';
import { resolveRobots } from 'next/dist/build/webpack/loaders/metadata/resolve-route-data';

export async function GET() {
  const { serverRuntimeConfig } = getConfig();
  const isProduction = serverRuntimeConfig.environment === 'production';
  const cacheControl = 'public, max-age=31536000'; // 31536000 seconds is approximately 1 year

  console.log(serverRuntimeConfig, isProduction);

  const headers = new Headers();
  headers.set('Cache-Control', cacheControl);
  headers.set('Content-Type', 'text/plain');

  const robots = resolveRobots({
    rules: {
      userAgent: '*',
      ...(isProduction && { allow: '/' }),
      ...(!isProduction && { disallow: '/' }),
    },
    sitemap: 'https://google.com/sitemap.xml',
  });

  return new Response(robots, { headers });
}


Thanks in advance! 🙏

11 Replies

so I am not able to allow/disallow depending of env
you can't use process.env.NODE_ENV inside the function to disallow/allow depending of your env?
@B33fb0n3 you can't use process.env.NODE_ENV inside the function to disallow/allow depending of your env?
Devon RexOP
I'd love to have it at runtime instead of build time, I did try within the process.env.NODE_ENV but same issue 😒
@B33fb0n3 you can't use process.env.NODE_ENV inside the function to disallow/allow depending of your env?
Devon RexOP
but no, that does not get updated at runtime, the file statically generated as per 😒
well, time to app/robots.txt/route.ts
@Devon Rex but no, that does not get updated at runtime, the file statically generated as per 😒
but have you tried export const revalidate = 0 inside the robots.ts file?
@joulev but have you tried `export const revalidate = 0` inside the `robots.ts` file?
Devon RexOP
yep, same as above (static)
@joulev well, time to app/robots.txt/route.ts
Devon RexOP
same thing T_T
@Devon Rex same thing T_T
// app/routes.txt/route.ts
import type { MetadataRoute } from "next";
import { resolveRobots } from "next/dist/build/webpack/loaders/metadata/resolve-route-data";

export function GET() {
  // TODO: Do something to get this object
  const robotObject: MetadataRoute.Robots = {
    rules: {
      userAgent: "*",
      allow: "/",
      disallow: "/private/",
    },
    sitemap: "https://acme.com/sitemap.xml",
  };
  const robotTxtContent = resolveRobots(robotObject);
  return new Response(robotTxtContent, { headers: { "Content-Type": "text/plain" } });
}

export const dynamic = "force-dynamic";