Next.js is a powerful React framework that enables you to build server-side rendering and static web applications with ease. One common task in web development is making API requests, and Axios is a popular library that simplifies this process. In this article, we’ll explore how to handle API requests in a Next.js application using Axios, including setting up Axios interceptors for request and response handling.
Why Use Axios?
Axios is a promise-based HTTP client for JavaScript that can be used in both the browser and Node.js. Here are some of the reasons why developers prefer Axios:
- Ease of Use: Axios has a simple and intuitive API that makes sending HTTP requests straightforward.
- Interceptors: Axios allows you to intercept requests or responses before they are handled by
then
orcatch
. - Transforming Requests and Responses: Axios can transform requests and responses data before they are handled.
- Automatic JSON Data Transformation: Axios automatically transforms JSON data.
- Wide Browser Support: Axios supports older browsers.
Setting Up Axios in a Next.js Project
To get started, you’ll need a Next.js project. If you don’t already have one, you can create it using:
npx create-next-app my-nextjs-app
cd my-nextjs-app
Then, install Axios by running:
npm install axios
Configuring Axios with Interceptors
Axios interceptors allow you to run your code or modify the request/response before they are handled by then
or catch
. This is especially useful for tasks such as attaching authentication tokens to requests and handling errors globally.
Creating an Axios Instance with Interceptors
Let’s create a custom Axios instance with request and response interceptors. Create a new file utils/axiosInstance.js
:
- Creating an Axios Instance:
import axios from "axios";
// Axios Interceptor Instance
const AxiosInstance = axios.create({
baseURL: process.env.BASE_URL
});
We create an Axios instance with a base URL from the environment variables. This helps in managing the API endpoint centrally.
2. Request Interceptor:
AxiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
const accessToken = JSON.parse(token);
// If token is present, add it to request's Authorization Header
if (accessToken) {
if (config.headers) config.headers.token = accessToken;
}
return config;
},
(error) => {
// Handle request errors here
return Promise.reject(error);
}
);
- Before a request is sent, the interceptor checks for a token in the local storage.
- If a token is found, it is added to the request headers.
- This is useful for authenticated endpoints where the server expects a token.
3. Response Interceptor:
// Axios Interceptor: Response Method
AxiosInstance.interceptors.response.use(
(response) => {
// Can be modified response
return response;
},
(error) => {
// Handle response errors here
return Promise.reject(error);
}
);
- After a response is received, the interceptor can modify it if needed.
- Any errors during the response can be handled globally.
export default AxiosInstance;
Using the Custom Axios Instance in Next.js
Now that we have our Axios instance set up, we can use it in our Next.js components or pages to make API requests.
Let’s make a GET request using our custom Axios instance in a Next.js component. Create a new file pages/index.js
:
import { useEffect, useState } from 'react';
import AxiosInstance from '../utils/axiosInstance';
const Home = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
AxiosInstance.get('/data')
.then(response => {
setData(response.data);
})
.catch(error => {
setError(error.message);
});
}, []);
if (error) return <div>Error: {error}</div>;
if (!data) return <div>Loading...</div>;
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default Home;
Using Axios in getStaticProps
or getServerSideProps
Next.js provides getStaticProps
and getServerSideProps
for data fetching at build time and request time, respectively.
Using getStaticProps
getStaticProps
is used for static generation. This means the data is fetched at build time.
import AxiosInstance from '../utils/axiosInstance';
export const getStaticProps = async () => {
try {
const response = await AxiosInstance.get('/data');
return {
props: {
data: response.data,
},
};
} catch (error) {
return {
props: {
error: error.message,
},
};
}
};
const Home = ({ data, error }) => {
if (error) return <div>Error: {error}</div>;
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default Home;
Using getServerSideProps
getServerSideProps
is used for server-side rendering. This means the data is fetched on each request.
import AxiosInstance from '../utils/axiosInstance';
export const getServerSideProps = async () => {
try {
const response = await AxiosInstance.get('/data');
return {
props: {
data: response.data,
},
};
} catch (error) {
return {
props: {
error: error.message,
},
};
}
};
const Home = ({ data, error }) => {
if (error) return <div>Error: {error}</div>;
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default Home;
Conclusion
Handling API requests in Next.js is straightforward with Axios. By setting up Axios interceptors, you can manage authentication tokens and handle errors globally, making your code cleaner and more maintainable. Whether you’re making requests in a component or during server-side rendering, Axios provides a simple and consistent API that integrates well with Next.js.
With the power of Axios and Next.js, you can build robust and efficient web applications that provide a seamless user experience.
Happy coding!