nextjs
  1. nextjs-data-fetching-in-nextjs

Data Fetching in Next.js

With Next.js, data fetching is made easy. It offers a variety of built-in ways to fetch data from various sources, depending on your needs. In this guide, we will explore different ways to fetch data and how to use it in Next.js.

Syntax

Server-side Rendering (SSR)

export async function getServerSideProps(context) {
  // fetch data from external API
  const res = await fetch(`https://api.example.com/data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

Static Site Generation (SSG)

export async function getStaticProps() {
  // fetch data from external API
  const res = await fetch(`https://api.example.com/data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

Client-side Data Fetching

import { useEffect, useState } from 'react'

export default function MyComponent() {
  const [data, setData] = useState([])

  useEffect(() => {
    async function fetchData() {
      const res = await fetch(`https://api.example.com/data`)
      const newData = await res.json()
      setData(newData)
    }

    fetchData()
  }, [])

  return (
    <div>
      {data.map(entry => (
        <div key={entry.id}>
          <h2>{entry.title}</h2>
          <p>{entry.content}</p>
        </div>
      ))}
    </div>
  )
}

Example

Server-side Rendering (SSR) Example

export async function getServerSideProps(context) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts`)
  const data = await res.json()

  return { props: { data } }
}

export default function Index({ data }) {
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(entry => (
          <li key={entry.id}>
            <h2>{entry.title}</h2>
            <p>{entry.body}</p>
          </li>
        ))}
      </ul>
    </div>
  )
}

Static Site Generation (SSG) Example

export async function getStaticProps() {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts`)
  const data = await res.json()

  return { props: { data } }
}

export default function Index({ data }) {
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(entry => (
          <li key={entry.id}>
            <h2>{entry.title}</h2>
            <p>{entry.body}</p>
          </li>
        ))}
      </ul>
    </div>
  )
}

Client-side Data Fetching Example

import { useEffect, useState } from 'react'

export default function Index() {
  const [data, setData] = useState([])

  useEffect(() => {
    async function fetchData() {
      const res = await fetch(`https://jsonplaceholder.typicode.com/posts`)
      const newData = await res.json()
      setData(newData)
    }

    fetchData()
  }, [])

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(entry => (
          <li key={entry.id}>
            <h2>{entry.title}</h2>
            <p>{entry.body}</p>
          </li>
        ))}
      </ul>
    </div>
  )
}

Output

The output of the above examples will be a list of posts fetched from JSONPlaceholder API.

Explanation

Next.js provides several methods for fetching data depending on your use case. The three main approaches are:

  • Server-side Rendering (SSR): This approach fetches data at runtime on the server before the page is rendered and returned to the client.
  • Static Site Generation (SSG): This approach fetches data at build time and generates static HTML pages that are served to the client when requested.
  • Client-side Data Fetching: This approach fetches data after the page has been rendered on the client-side using the useEffect hook.

Use

Use data fetching in Next.js to fetch data from APIs, databases or any other sources required to render pages.

Important Points

  • Use getServerSideProps for server-side rendering and getStaticProps for static site generation.
  • Client-side data fetching can be done using the useEffect hook.
  • Data fetched on the server is not available on the client-side until it has been serialized and sent with the page.
  • SSG is recommended for performance and SEO, but SSR might be needed in some cases like fetching the most updated data.
  • Use a library like Axios to handle HTTP requests and improve readability of data fetching code.

Summary

Data fetching in Next.js is made easy with several built-in methods depending on the needs of your application. By understanding how these methods work and when to use each one, you can optimize the performance and SEO of your application.

Published on: