api integration for web pages in next js

  1. Install Axios: Install Axios, a promise-based HTTP client, to make API requests.

    bash npm install axios

  2. 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' }); } } ```

  3. Fetch Data in a Page Component: In your page component (e.g., pages/index.js), fetch data from the API using the fetch or axios 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; ```

  4. Run Your Next.js App: Start your Next.js development server.

    bash npm run dev

  5. Access the Page: Open your browser and go to http://localhost:3000 to see the integrated data from the API.

  6. 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.