Danilo-Guedes
Danilo-Guedes

Reputation: 141

Can Axios be used in new next.js 13 instead of extended next fetch api version?

  1. Hey guys, can I use axios with next.js 13 and still get the same results of their extended fetch api version with cache and revalidate configs ??

  2. Is axios going to this web-standard thing direction ??

  3. I realy love axios.intereceptors functionality , should I use next middlewares instead?

please can I have yall 2 cents?

My first stackoverflow question, even coding for 2 years (still) ... please vote up so I can unlock the mid dev super powers tks

`export default async function Page() {
  // revalidate this data every 10 seconds at most
  const res = await **axios.get**('https://...', { next: { revalidate: 10, cache: 'force-cache' .... } });
  const data = res.json();
  // ...
}

// does axios setup the config correctly ?

Upvotes: 14

Views: 32599

Answers (2)

If you check the documentation on "Data Fetching > Caching" they comments about the React cache() wrapper. This is a way that you should be caching other libraries or data fetching process on server side components, an example:


// On getSome.js

export const getSome = cache( async() => {
    const res = await axios.get('https://...', otherAxiosConfigObject);
    const data = res.json();
    return data;
})


// On Page (or component)

export const revalidate = 10; //revalidate every 10 seconds

export default async function Page() {
  const someData = await getSome();
}

With this approach, you can call getSome() async function in any components, and NextJS apply deduping at building time for do only one fetch process.

Upvotes: 16

Brukols
Brukols

Reputation: 101

According to the documentation, it's not currently possible to use axios to revalidate data by passing the same arguments as one might do with the fetch API.

Nonetheless, there is a workaround available as a temporary solution. You can add the following line to the top of your file :

export const revalidate = 3600;  // revalidate every hour

After doing this, all your requests will be subject to revalidation after a certain period. Please bear in mind, this is merely a temporary solution and lacks the efficiency of the fetch API.

It seems that Next.js intends to implement caching and revalidation configurations for third-party services in the future. However, as of now, this functionality is not available.

I highly recommend you refer to the Next.js documentation for more details : https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#data-fetching-without-fetch

Upvotes: 4

Related Questions