You’ve probably seen getServerSideProps
in plenty of Next.js tutorials. But when it comes to calling an external API inside it — and doing it properly — things can get a little messy.
Should you fetch directly? What about error handling? How do you avoid slowing down your whole page?
In this chapter, we’ll walk through exactly how to use getServerSideProps
with external APIs, and how to do it in a way that won’t break your app (or your API provider’s rate limits).
What is getServerSideProps
?
- Special Next.js function that runs only on the server
- Runs on every request — perfect for real-time, fresh data
- Used in the
pages/
directory only
Syntax Recap
export async function getServerSideProps(context) { // Fetch data return { props: {}, // passed to component as props }; }
Fetching External API Data
Example with Fetch
export async function getServerSideProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await res.json(); return { props: { posts: data }, }; } export default function BlogPage({ posts }) { return ( <div> <h1>Latest Blog Posts</h1> {posts.map((post) => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.body}</p> </div> ))} </div> ); }
External API Tips
- Handle errors — always use try/catch
- Avoid long API timeouts — set reasonable timeout limits
- Avoid overloading the API — respect rate limits
- Keep sensitive tokens server-side — never expose them in client code

Example with Error Handling
export async function getServerSideProps() { try { const res = await fetch('https://api.example.com/data'); if (!res.ok) throw new Error('Failed to fetch'); const data = await res.json(); return { props: { data } }; } catch (error) { console.error(error); return { props: { data: null, error: 'Failed to load data' } }; } }
When to Use
- Real-time data
- Authenticated requests
- Personalization
- External APIs with rapidly changing data
When NOT to Use
- For static pages, use SSG or ISR instead
- For public data that rarely changes, SSG or ISR will be faster and cheaper
Final Thought
Knowing when and how to use getServerSideProps
gives you one more powerful tool in your Next.js toolbox — especially when real-time APIs are involved.
But remember: this is for the pages/
directory only. If you’re using the App Router (app/
directory), you’ll want to lean on React Server Components instead.
Next up: Streaming Layouts + Suspense in React Server Components
In the next chapter, we’ll explore how to create apps that feel lightning fast using streaming layouts and React’s Suspense to deliver content progressively. It’s where Next.js really starts to shine. See you there!