Server-side rendering with parallel data loading
Show how to use `getServerSideProps` to load data in parallel from multiple sources before rendering a Next.js page server-side.
import { promises as fs } from 'fs';
import path from 'path';
export async function getServerSideProps(context) {
// Use Promise.all to load data in parallel
const [userData, productData] = await Promise.all([
fetch('https://api.example.com/users').then(res => res.json()),
fetch('https://api.example.com/products').then(res => res.json()),
// ... add more promises for additional data sources
]);
// Return the data for server-side rendering
return {
props: { userData, productData }, // will be passed to the page component as props
};
}
export default function Page({ userData, productData }) {
// Render the page with the data loaded server-side
return (
<div>
<h1>Users</h1>
{/* render users */}
<h1>Products</h1>
{/* render products */}
</div>
);
}
This code defines a Next.js page with server-side rendering. The `getServerSideProps` function is used to fetch user and product data from two different APIs in parallel using `Promise.all`. The fetched data is then passed as props to the page component, which renders the page with the server-side loaded data.