Skip to content Skip to sidebar Skip to footer

Internal Api Fetch With Getserversideprops? (next.js)

I'm new to Next.js and I'm trying to understand the suggested structure and dealing with data between pages or components. For instance, inside my page home.js, I fetch an internal

Solution 1:

But then I read in the Next.js documentation that you should not use fetch() to all an API route in getServerSideProps().

You want to use the logic that's in your API route directly in getServerSideProps, rather than calling your internal API. That's because getServerSideProps runs on the server just like the API routes (making a request from the server to the server itself would be pointless). You can read from the filesystem or access a database directly from getServerSideProps.

(Note that the same applies when using getStaticProps/getStaticPaths methods)


Here's a small refactor example that allows you to have logic from an API route reused in getServerSideProps.

Let's assume you have this simple API route.

// pages/api/userexportdefaultasyncfunctionhandler(req, res) {
    // Using a fetch here but could be any async operation to an external sourceconst response = awaitfetch(/* external API endpoint */)
    const jsonData = await response.json()
    res.status(200).json(jsonData)
}

You can extract the fetching logic to a separate function (can still keep it in api/user if you want), which is still usable in the API route.

// pages/api/userexportasyncfunctiongetData() {
    const response = awaitfetch(/* external API endpoint */)
    const jsonData = await response.json()
    return jsonData
}

exportdefaultasyncfunctionhandler(req, res) {
    const jsonData = awaitgetData()
    res.status(200).json(jsonData)
}

But also allows you to re-use the getData function in getServerSideProps.

// pages/homeimport { getData } from'./api/user'//...exportasyncfunctiongetServerSideProps(context) {
    const jsonData = awaitgetData()
    //...
}

Solution 2:

Just try to use useSWR, example below

import useSWR from'swr'importReactfrom'react';

//important to return only result, not Promiseconstfetcher = (url) => fetch(url).then((res) => res.json());

constCategories = () => {
 //getting data and errorconst { data, error } = useSWR('/api/category/getCategories', fetcher)
 if (error) return<div>Failed to load</div>if (!data) return<div>Loading...</div>if (data){
   // {data} is completed, it's ok!//your code here to make something with {data}return (
      <div>
      //something here, example {data.name}
      </div>
   )
 }
}

exportdefaultCategories

Please notice, fetch only supports absolute URLs, it's why I don't like to use it.

P.S. According to the docs, you can even use useSWR with SSR.

Post a Comment for "Internal Api Fetch With Getserversideprops? (next.js)"