Home > Article > Web Front-end > Should You Use `fetch()` for Internal API Calls in `getServerSideProps` (Next.js)?
In Next.js, the getServerSideProps function allows you to fetch data from the server before rendering a page, making it suitable for SEO. However, the official documentation advises against using fetch() to call internal API routes within getServerSideProps.
Reason for Avoidance
Calling an internal API route from getServerSideProps is redundant because both run on the server. Instead, the logic from the API route should be directly implemented in getServerSideProps to avoid unnecessary HTTP requests.
Alternative Approach
To utilize the logic from an API route in getServerSideProps:
Example
pages/api/user.js (API route with shared logic)
import { getData } from "./userData"; export async function handler(req, res) { const data = await getData(); res.status(200).json({ data }); }
pages/home.js (getServerSideProps using shared logic)
import { getData } from "./api/user"; export async function getServerSideProps(context) { const data = await getData(); // ... other operations ... }
The above is the detailed content of Should You Use `fetch()` for Internal API Calls in `getServerSideProps` (Next.js)?. For more information, please follow other related articles on the PHP Chinese website!