Effortless Next.js Data Fetching with SWR, and Axios
In the fast-paced world of web development, data fetching plays a pivotal role in building dynamic and responsive web applications.

Developers are continually seeking ways to simplify this process while ensuring that their applications remain performant and efficient. Enter Next.js, SWR (Stale-While-Revalidate), and Axios — a triumphant trio that empowers developers to fetch and manage data with unprecedented ease.
In this article, we embark on a journey into the realm of Next.js, SWR, and Axios, exploring how this combination can revolutionize data fetching in your Next.js applications.
Requirement:
Before we proceed further, let’s make sure we have the necessary software.
Software:
1. Setup Project
Run the following command in your terminal/cmd
$ yarn create next-app next-swr-axios2. Install Dependencies
You now have a new directory called next-swr-axios. Let’s cd into it:
$ cd next-swr-axiosNext, install dependencies
$ yarn add swr axiosExplanation :
- swr : a React Hooks library for data fetching
- axios : a promise-based HTTP Client for node.js and the browser.
3. Configure Environment
By using a .env file, you can easily manage and update configuration settings without hardcoding them in your code.
This approach enhances security and maintainability since sensitive information is kept separate from your source code and can be easily changed as needed without altering the application's codebase.
Additionally, the NEXT_PUBLIC_ prefix in this variable suggests that it is intended to be accessible on the client-side in a Next.js application, making it available to both the server and the browser.
Create .env file, and copy-paste this code below
NEXT_PUBLIC_API_HOST=https://crudcrud.com/api/184e182f1da846188b9abcd101b8c20b4. Keep configuration settings in a separate file
Create ./src/config/index.js, and copy-paste this code below
const config = {
API_HOST: process.env.NEXT_PUBLIC_API_HOST
};
export default config;5. Create Axios Instance
Create ./src/libs/utils/api.js, and copy-paste this code below
import axios from 'axios';
import config from '@/config';
const instance = axios.create({
baseURL: config.API_HOST,
timeout: 40000,
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json; charset=utf-8'
}
});
export const fetcher = (url) => {
return instance.get(url).then((res) => {
if (!res.data) {
throw Error(res.data.message);
}
return res.data;
});
};
export default instance;- An axios instance is created using
axios.create(). This instance allows you to define default configurations for your HTTP requests. baseURLis set toconfig.API_HOST, which specifies the base URL for all requests made with this instance. This can be useful for avoiding redundancy in your API URLs.- A timeout of 40,000 milliseconds (40 seconds) is set, which means that if a request takes longer than this time, it will be considered a timeout.
- Default headers are specified to ensure consistency in request headers, such as specifying the
AcceptandContent-Typeheaders for JSON requests.
5. Create hooks for fetching data
Create ./src/libs/hooks/unicorn.js, and copy-paste this code below
import useSWR from 'swr';
import { fetcher } from '@/libs/utils/api';
export const useUnicorns = () => {
const pathKey = `/unicorns`;
const { data, error } = useSWR(pathKey, fetcher, {
refreshInterval: 10000
});
return { data: data || [], loading: !error && !data };
};- The code imports the
useSWRhook from the 'swr' library. This hook is used for data fetching with SWR. - It also imports the
fetcherfunction from theapimodule, which is likely the function responsible for making HTTP requests using Axios.
useSWR is called with three arguments:
pathKey: This is the key representing the data you want to fetch. It's used to identify and cache the data.fetcher: This is likely a function responsible for making the actual HTTP request to fetch the data. It's provided touseSWRas a callback.{ refreshInterval: 10000 }: This is an optional configuration object that specifies a refresh interval of 10,000 milliseconds (10 seconds). It means that SWR will automatically revalidate (refetch) the data every 10 seconds, keeping it up to date.
useSWR returns an object with two properties:
data: This is the fetched data. If the data has not been fetched yet, it will beundefinedinitially.error: This holds any error that might occur during the data fetching process.
The useUnicorns custom hook returns an object with two properties:
data: This property contains the fetched data if it's available. If the data is still loading or has not been fetched yet, it defaults to an empty array ([]).loading: This is a boolean that istruewhen neither an error nor data is present. It'sfalsewhen data is available or an error has occurred.
6. Implement into Page
Copy-paste this code below into ./src/index.js
import { useUnicorns } from "@/libs/hooks/unicorn";
export default function Home() {
const { data } = useUnicorns();
return (
<div>
{data?.map((item) => (
<div>{item?.name}</div>
))}
</div>
);
}This code is a React component that fetches data using a custom hook called useUnicorns and then renders that data in a page named Home.
7. Result
Run the following command
$ yarn devThen your result will looks like this

Full source code : https://github.com/ryanadhitama/next-swr-axios/pull/1/files
Conclusion
Today, we learned how to integrate swr and axios in your Next.js project. We hope this tutorial will help other developers to make data fetching in Next.js project. Stay updated with our various other tutorials, and let’s connect on LinkedIn!
LinkedIn: https://www.linkedin.com/in/ryanadhitama/
In Plain English
Thank you for being a part of our community! Before you go:
- Be sure to clap and follow the writer! 👏
- You can find even more content at PlainEnglish.io 🚀
- Sign up for our free weekly newsletter. 🗞️
- Follow us on Twitter(X), LinkedIn, YouTube, and Discord.






