NextJS 13 Data Fetching – Fetch

by
Ali Hasan
axios fetch-api next.js

Quick Fix: To fetch data in Next.js 13, you can use the built-in fetch API. Here’s a quick example of how to use it:

const res = await fetch('https://example.com/api/data');
const data = await res.json();

This will fetch the data from the specified URL and parse the response as JSON. You can then use the data variable to access the fetched data.

The Problem:

How to set a custom base URL for the fetch method in Next.js 13?

The Solutions:

Solution 1: Use fetch() method

To fetch data from an endpoint using the native fetch() method, you can do the following:

// Fetch data with GET request
let data = await fetch('https://some-domain.com/api/');

// Fetch data with POST request
fetch("https://some-domain.com/api/", {
  method: "POST",
  body: JSON.stringify({
    your: data,
  }),
  headers: {
    "Content-Type": "application/json; charset=UTF-8",
  }
});

Solution 3: Using .env Files

You can use .env files to provide custom base URLs for your fetch method. This approach involves:

  1. Creating a .env file with your custom base URL:

    NEXT_PUBLIC_BASE_URL=https://my-custom-base-url.com
    
  2. Reading the base URL from the .env file in your components:

    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL;
    
  3. Using the base URL in your fetch request:

    fetch(`${baseUrl}/api/data`)
        .then(res => res.json())
        .then(data => console.log(data));
    

This method allows you to specify different base URLs for development and production environments by using separate .env files for each environment.

Q&A

How to fetch data using nativoe JS (Using Fetch method) ?

Just pass the url with fetch('url') to fetch the data from an end point and you will get the result.

Is there any way of using baseUrl for fetch Api ?

No, you can’t.

How to use baseUrl with help of .env-files ?

You can use .env-files to set a global "baseUrl" for development. Read the baseUrl using process.env and replace the url in your components.

Video Explanation:

The following video, titled "Next.js 13 Crash Course Tutorial #6 - Fetching & Revalidating Data ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this Next 13 tutorial series, you'll learn the basics of Next.js to make a simple project, using the new app router & server components.