0
0
NextjsHow-ToBeginner · 4 min read

How to Use Fetch in Next.js: Simple Guide with Examples

In Next.js, you can use the fetch API to get data either on the server side inside getServerSideProps or getStaticProps, or on the client side inside React components using hooks like useEffect. This lets you load data before rendering or dynamically after the page loads.
📐

Syntax

The basic syntax of fetch is calling fetch(url, options) which returns a promise. You then use await or .then() to get the response and convert it to JSON or text.

  • url: The address of the resource you want to get.
  • options: Optional settings like method, headers, body, etc.
  • response.json(): Parses the response body as JSON.
javascript
const response = await fetch('https://api.example.com/data');
const data = await response.json();
💻

Example

This example shows how to fetch data from an API inside getServerSideProps to load data on the server before rendering the page. The data is passed as props to the component and displayed.

javascript
export async function getServerSideProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const post = await res.json();

  return {
    props: { post },
  };
}

export default function PostPage({ post }) {
  return (
    <main>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </main>
  );
}
Output
<main><h1>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h1><p>quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto</p></main>
⚠️

Common Pitfalls

Common mistakes when using fetch in Next.js include:

  • Not awaiting the fetch call or the response.json() which causes unresolved promises.
  • Using fetch directly in the component without hooks, causing infinite loops.
  • Not handling errors, which can crash the app or show blank pages.
  • Trying to use fetch on the server side without await or outside data fetching methods.

Always use await and handle errors with try/catch or .catch().

javascript
/* Wrong: Missing await causes unresolved promise */
const data = fetch('https://api.example.com/data').then(res => res.json());

/* Right: Await the fetch and json parsing */
const response = await fetch('https://api.example.com/data');
const data = await response.json();
📊

Quick Reference

Tips for using fetch in Next.js:

  • Use getServerSideProps or getStaticProps for server-side data fetching.
  • Use useEffect with fetch for client-side data fetching.
  • Always await fetch and response.json().
  • Handle errors gracefully with try/catch.
  • Remember fetch is built-in in modern browsers and Node.js 18+ (Next.js uses Node.js 18+).

Key Takeaways

Use fetch with await inside Next.js data fetching methods or React hooks.
Always handle fetch errors to avoid app crashes.
Server-side fetch happens in getServerSideProps or getStaticProps for SEO benefits.
Client-side fetch should be done inside useEffect to avoid infinite loops.
Next.js supports native fetch in Node.js 18+, no extra libraries needed.