Blog>
Snippets

Server Actions with Third-party API Integration

Integrate a third-party API into a Next.js 14 server action, handling the request, response, and potential errors.
import axios from 'axios';

export const fetchFromApi = async (req, res) => {
  try {
    // Replace with the actual API endpoint you're using
    const apiUrl = 'https://api.example.com/data';

    // Replace with API-specific request configuration if needed
    const apiResponse = await axios.get(apiUrl);

    // Process the data as necessary
    const processedData = apiResponse.data; // This is a placeholder for any data processing logic

    // Return the processed data as a JSON response
    res.status(200).json(processedData);
  } catch (error) {
    // Return a JSON response with the error
    res.status(500).json({
      error: error.message || 'An unexpected error occurred',
    });
  }
};
Defines an async server action using Next.js API routes that fetches data from a third-party API using Axios. It processes the response and sends back the processed data or an error message if the request fails.