blog image

Data Fetching in Next.js

Data Fetching and data mutating is very important in web application. So, Next.js provide features like data fetching, data caching and revalidating.

Data Fetching with fetch

⚠️

Disclaimer: Next.js extends the native fetch Web API to allow you to configure the caching and revalidating behavior for each fetch request on the server. React extends fetch to automatically memoize fetch requests while rendering a React component tree.

You can use fetch with async/await in Server Components, in Route Handlers, and in Server Actions.

Server Side Data Fetching

'use server';
 
export const getData = async () => {
  const response = await fetch('https://yourapi.com/api/route');
  if (!response.ok) throw new Error('Server Error');
  return await response.json();
};
import { getData } from '_action.ts';
const page = async () => {
  const data = await getData();
  return (
    <div>
      {/*{
            data ui logic
        }*/}
    </div>
  );
};
 
export default page;

Client Side Data Fetching

'use client';
import { useEffect, useState } from 'react';
const page = () => {
  const [data, setData] = useState<null | []>(null);
  const [error, setError] = useState('');
  useEffect(() => {
    fetch('https://yourapi.com/api/route')
      .then((res) => res.json())
      .then((res) => setData(res))
      .catch((e) => setError(e));
  }, []);
  return <div></div>;
};
 
export default page;
⚠️

You can also fetch data on the client using a third-party library such as swr or TanStack Query.

Server Components and Route Handlers Since Server Components render on the server, you don't need to call a Route Handler from a Server Component to fetch data. Instead, you can fetch the data directly inside the Server Component.

Enjoyed the article? 😍