Blog>
Snippets

Simple parallel data fetching with `Promise.all`

Demonstrate how to fetch data from multiple API endpoints in parallel using `Promise.all` within a Next.js API route handler.
import fetch from 'node-fetch';

export default async function handler(req, res) {
  const urls = [
    'https://api.first-endpoint.com/data',
    'https://api.second-endpoint.com/data',
    'https://api.third-endpoint.com/data'
  ];

  try {
    // Use Promise.all to fetch the data from all URLs in parallel
    const dataPromises = urls.map(url => fetch(url).then(response => response.json()));
    const results = await Promise.all(dataPromises);

    // Send back the combined results as a response
    res.status(200).json({ data: results });
  } catch (error) {
    // Handle errors
    res.status(500).json({ error: error.message });
  }
}
This Next.js API route handler uses `node-fetch` to perform parallel data fetching from multiple API endpoints using `Promise.all`. It maps over an array of API endpoint URLs, creating a promise for each fetch request, then awaits the resolution of all these promises. If successful, it sends back a combined result; if there is an error, it sends a 500 response with the error message.