Data Fetching

Learn about data fetching techniques in Next.js.

Fetching techniques in Next.js

Next.js allows us to fetch data on both the client and server sides. Server-side data fetching could happen in two different moments:

  • At build time using getStaticProps for static pages

  • At runtime using getServerSideProps for server-side rendered pages

Data can come from several resources: databases, search engines, external APIs, filesystems, and many other sources. Even if it’s technically possible for Next.js to access a database and query for specific data, we discourage that approach because Next.js should only care about the frontend of our application.

Let’s take an example: we’re building a blog, and we want to display an author page showing their name, job title, and biography. In that example, the data is stored in a MySQL database, and we could easily access it using any MySQL client for Node.js.

Even though accessing that data from Next.js can be relatively easy, it would make our app less secure. A malicious user could potentially find a way to exploit our data using an unknown framework vulnerability, injecting malicious code and using other techniques to steal our data.

For that reason, we strongly suggest delegating database connections and queries to external systems like CMSes, such as WordPress, Strapi, and Contentful, or back-end frameworks, such as Spring, Laravel, and ...