Aayush Neupane
Aayush Neupane

Reputation: 1246

fetching data in Next.js

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

above sentence is from official docs of next.js and i find it confusing.
is it saying that i shouldn't do ajax request to my restful api? (i m using node express app as backend).
i m new to next.js, before i was using react node app with mongodb as database. i used moongose package for database related queries.
if i am not supposed to do ajax request then how am i supposed to work with data fetching related thing? can i use moongose in frontend directly?

//the way i want to do   
 getStaticProps(){
    //here i want to get data from database about posts
    //fetch('some end point of my restful api'){...}
    }
//the way i think official docs is telling me to do
     getStaticProps(){
        //query from database

    
        }

Upvotes: 1

Views: 8388

Answers (1)

Ramakay
Ramakay

Reputation: 3135

API Routes are a NextJS feature that let you create a API - This requires the local server to be up and listening.

https://nextjs.org/docs/api-routes/introduction

getStaticProps are fetched at build time, means without user request. It lets NextJS generate SSR pages without needing a user request, API Routes wont be available at this time as the server hasn't started.

In your example

    //here i want to get data from database about posts
    //fetch('some end point of my restful api'){...}
// 1.Write your data from database 
// 2. Instead of `fetch` - Write logic of your restful api if 
its internal or the external endpoint that doesn't 
need the instantiation of your server.

Hope the difference makes sense, you can make fetch calls its just that they shouldn't be something your server itself is creating. Think of it like a build time fetch call.

Upvotes: 4

Related Questions