api integration for web pages in next js
Install Axios: Install Axios, a promise-based HTTP client, to make API requests.
bash npm install axios
Create an API Function: In the
pages/api
directory, create a file (e.g.,example.js
). Define an API route using Next.js API routes.```jsx // pages/api/example.js import axios from 'axios';
export default async function handler(req, res) { try { const response = await axios.get('https://api.example.com/data'); const data = response.data; res.status(200).json(data); } catch (error) { console.error('API Error:', error.message); res.status(500).json({ error: 'Internal Server Error' }); } } ```
Fetch Data in a Page Component: In your page component (e.g.,
pages/index.js
), fetch data from the API using thefetch
oraxios
library.```jsx // pages/index.js import { useEffect, useState } from 'react'; import axios from 'axios';
const Home = () => { const [data, setData] = useState(null);
useEffect(() => { const fetchData = async () => { try { const response = await axios.get('/api/example'); setData(response.data); } catch (error) { console.error('Fetch Error:', error.message); } };
fetchData();
}, []);
return (
); };API Integration with Next.js
{data && (-
{data.map((item) => (
- {item.name} ))}
export default Home; ```
Run Your Next.js App: Start your Next.js development server.
bash npm run dev
Access the Page: Open your browser and go to
http://localhost:3000
to see the integrated data from the API.Deploy Your Next.js App: Deploy your app to a hosting service of your choice, ensuring that the API routes are correctly configured.
bash npm run build npm start
Ensure your hosting provider supports Node.js and the configuration for serverless functions or API routes.