Data Fetching
Explore data fetching in Next.js including server-side and static generation techniques. Understand how to securely consume public and private REST APIs using authorization methods and environment variables for tokens. Learn to handle errors and implement dynamic routing for scalable web applications.
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
getStaticPropsfor static pagesAt runtime using
getServerSidePropsfor 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 ...