Cholewka
Cholewka

Reputation: 983

Next.js not build when using getStaticPaths and props

I'm trying to run next build when using getStaticProps and getStaticPaths method in one of my routes, but it fails every time. Firstly, it just couldn't connect to my API (which is obvious, they're created using Next.js' API routes which are not available when not running a Next.js app). I thought that maybe running a development server in the background would help. It did, but generated another problems, like these:

Error: Cannot find module for page: /reader/[id]
Error: Cannot find module for page: /
> Build error occurred
Error: Export encountered errors on following paths:
        /
        /reader/1

Dunno why. Here's the code of /reader/[id]:

const Reader = ({ reader }) => {
  const router = useRouter();

  return (
    <Layout>
      <pre>{JSON.stringify(reader, null, 2)}</pre>
    </Layout>
  );
};

export async function getStaticPaths() {
  const response = await fetch("http://localhost:3000/api/readers");
  const result: IReader[] = await response.json();

  const paths = result.map((result) => ({
    params: { id: result.id.toString() },
  }));

  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  const res = await fetch("http://localhost:3000/api/readers/" + params.id);
  const result = await res.json();
  return { props: { reader: result } };
}

export default Reader;

Nothing special. Code I literally rewritten from the docs and adapted for my site.

And here's the /api/readers/[id] handler.

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const knex = getKnex();
  const { id } = req.query;

  switch (req.method) {
    case "GET":
      try {
        const reader = await knex
          .select("*")
          .from("readers")
          .where("id", id)
          .first();

        res.status(200).json(reader);
      } catch {
        res.status(500).end();
      }

      break;
  }
}

Nothing special either. So why is it crashing every time I try to build my app? Thanks for any help in advance.

Upvotes: 0

Views: 1513

Answers (1)

Anish Antony
Anish Antony

Reputation: 1515

You should not fetch an internal API route from getStaticProps — instead, you can write the fetch code present in API route directly in getStaticProps.

https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly

Upvotes: 1

Related Questions