1

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

    
        }

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so next.js lets me write backend code? can i use mongoose? thanks i got my answer i have different api exposed as a backend for my app so i can call fetch the docs was talking about diiferent api route ie provided by next.js.am i right?
Correct, anything that is not created by the app itself - write your code to access mongoose there just be aware thay page creation may take longer during build time but pages can will be super fast!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.