Search code examples
next.jsssg

Is it possible to use API Routes for building pages in Next.JS getStaticProps/getStaticPaths?


I'm making static Next.JS app with MongoDB.

In my static Next.JS app can I use api routes for building pages? For example, using GET method for getting products in getStaticProps? Or it's bad approach.

Now I'm using classic way from documentation (direct calls to db, like find etc).


Solution

  • You probably can but it's a bad practice to use API routes in getStaticProps/getStaticPaths as stated in the docs.

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

    Note: You should not use fetch() to call an API route in getServerSideProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!