Server-side Rendering using getServerSideProps
Server-side Rendering (SSR) in Next.js involves fetching data on each request from the server before rendering the page. This ensures that the content is always up-to-date and can be personalized for each user. SSR is suitable for pages with dynamic content or data that changes frequently.
How it Works:
- When a user visits an SSR-enabled page, Next.js calls getServerSideProps.
- Inside getServerSideProps, you can fetch data from an API, database, or any other source.
- Next.js then generates the HTML for the page with the fetched data and sends it to the client.
Use Cases:
- Pages with dynamic content (e.g., user dashboards, real-time analytics).
- Personalized content based on user sessions or preferences.
- Ensuring data freshness for each user visit.
Syntax:
export async function getServerSideProps() {
// Fetch data from an API or database
const data = await fetchData();
return {
props: {
data,
},
};
}
Example: Below is an example of fetching data using getServerSideProps in NextJS App.
// product/[id].js
export default function Product({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
export async function getServerSideProps(context) {
const { params } = context;
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/[id]`);
const data = await res.json();
return {
props: {
data,
},
};
}
Output
How to Fetch data faster in Next.js?
NextJS, a popular React framework provides various approaches to fetch data efficiently. Optimizing data fetching can significantly improve the performance and user experience of your NextJS applications.
We will discuss different approaches to Fetch data faster in NextJS:
Table of Content
- Static Generation using getStaticProps
- Server-side Rendering using getServerSideProps
- Client-side Data Fetching with useSWR and fetch