Data Fetching
Learn about data fetching techniques in Next.js.
We'll cover the following...
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 pagesAt 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 Ruby on Rails, which will make sure that the data is coming from a trusted source, will sanitize the user input detecting potentially malicious code, and will establish a secure connection between our Next.js application and their APIs.
In the following sections, we’ll see how to integrate REST and GraphQL APIs from both the client side and the server side.
Fetching data on the server side
As we've seen so far, Next.js allows us to fetch data on the server side by using its built-in getStaticProps
and getServerSideProps
functions.
Given that Node.js doesn’t support JavaScript fetch
APIs like browsers do, we have two options for making HTTP requests on the server: ...