0

I am trying to create a dynamic robots.txt file in my next.js app. The api route solution suggested by @juliomalves works well: Generating a dynamic /robots.txt file in a Next.js app

Until the rewrite, which returns a '404 Not Found' for me. What am I not seeing?!

Rewrite logic in next.config.js, based on next.js docs:

async rewrites() {
        return [
            {
                source: `/robots.txt`,
                destination: `/api/robots`
            }
        ];
    },

'pages/api/robots'

import React from "react";
import { GetServerSideProps } from "next";

const rootUrl = process.env.PUBLIC_URL

const robotsResponse = "content"

export const getServerSideProps : GetServerSideProps = async (context) => {
    const { res } = context;

    res.write(robotsResponse);
    res.end();

    return(
        <>{res}</>
    );
};


export default getServerSideProps;

But when I access '/robots.txt', I receive a '404 Not Found'. Any ideas anyone?

Simon Gowing
  • 241
  • 1
  • 2
  • 10
  • `getServerSideProps` is used in pages. That's not the format the function should have in an API route. See https://nextjs.org/docs/api-routes/introduction. – juliomalves Feb 15 '22 at 09:42
  • Also, make sure to restart your dev server after changing the `next.config.js` file, it's required for Next.js to pick up the changes made there. – juliomalves Feb 15 '22 at 09:54

0 Answers0