How to Implement Server-Side Rendering (SSR) with Data Fetching?
asked 229 days ago
0Answers
10Views
Hey everyone! I'm working on a Next.js project and I'm trying to incorporate server-side rendering (SSR) while fetching data. I want to optimize my application for better performance and SEO. Can anyone guide me through the best practices or provide a code example on how to achieve SSR with data fetching using Next.js? Any insights or pointers would be highly appreciated! Thanks in advance.
// pages/examplePage.js
import React from 'react';
import fetch from 'isomorphic-unfetch';
const ExamplePage = ({ data }) => {
// Render data fetched from server
return (
<div>
<h1>Server-Side Rendering with Data Fetching</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
};
export async function getServerSideProps() {
// Fetch data on the server-side
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }, // Pass fetched data as props
};
}
export default ExamplePage;