1. Create or Modify a Page Component
Suppose you have a page component named MyPage.js
where you want to implement SSR. Your file structure might look something like this:
pages/
└── mypage.js
2. Use getServerSideProps
for Data Fetching
In your MyPage.js
file, you will define the getServerSideProps
function. This function runs on the server at every request, allowing you to fetch data from an external API.
Here's an example:
// pages/mypage.js
import React from 'react';
// Define the MyPage component
const MyPage = ({ data }) => {
return (
<div>
<h1>Data fetched from API:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
// Fetch data from the API using getServerSideProps
export async function getServerSideProps() {
// Replace with your API endpoint
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Always return an object with props
return {
props: {
data, // This will be passed as props to the MyPage component
},
};
}
export default MyPage;
3. Explanation of the Code
-
getServerSideProps
: This is an async function that runs on the server side before rendering the page. It fetches the data from the API and returns it as props to the page component. -
fetch
: Thefetch
function is used to make an HTTP request to the API. This is where you would replace'https://api.example.com/data'
with your actual API endpoint. -
Returning Props: The object returned by
getServerSideProps
must include aprops
key. This object is passed to the page component as props, allowing the component to use the fetched data. -
Component Rendering: Inside the
MyPage
component, the fetched data is displayed. In this example, the data is rendered in a<pre>
tag to format it nicely.