Home > Mobile >  Next.js and generating static site plus API in the same project
Next.js and generating static site plus API in the same project

Time:06-06

I have a project using Next with both an API that feeds data from a SQLite database and a front-end to consume and display it.

Plan would be to export it as a static site since data is pretty much unchanging, but I get an error when trying to build the project because the fetch urls depend on the project running (currently just using fixed local port).

What would be the appropriate approach here? Should I separate the API from the front-end? Or is there a way to do both within the same project accounting for the static export?

(Sorry if the question is kind of stupid, as this is my first time using Next.js and experimenting with static sites. Any input is appreciated.)

CodePudding user response:

The better approach would be, serve data from getStaticProps method.

Here in getStaticProps method you need to directly call your helper function to get data from DB because you can't call your Nextjs APIs in getStaticProps method because it is executed while build time.

Example:

export const getStaticProps = async (context) => {
   // get async data
   const dbData = await dbHelper();
   return {
      props: {
        data: dbData
      }
   };
};

You will receive this data as a prop in the page component.

Note: getStaticProps method must be exported from a file in the pages folder.

  • Related