Advantages of getServerSideProps:
- Real-time Data: Each page request retrieves fresh data.
- SEO Benefits: Search engines can index your content because the HTML is pre-rendered on the server.
- Personalization: You can personalize content based on request parameters (such as query strings or headers).
Limitations of getServerSideProps:
- Performance: Since the page is generated on each request, it can lead to longer page load times compared to static generation.
- No Caching:
getServerSideProps doesn’t cache the data automatically. If you need caching, you can implement it manually (e.g., with a CDN or caching headers).
// pages/profile.js
import axios from 'axios';
const ProfilePage = ({ user }) => {
if (!user) {
return <div>Please log in to see your profile.</div>;
}
return (
<div>
<h1 className="text-3xl font-bold mb-4">Welcome, {user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
};
export async function getServerSideProps(context) {
// Get the user authentication token (e.g., from cookies or headers)
const token = context.req.cookies.token;
if (!token) {
// Redirect to login page if not authenticated
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
try {
// Fetch user data from API using the token
const response = await axios.get('https://api.example.com/profile', {
headers: {
Authorization: `Bearer ${token}`,
},
});
const user = response.data;
return {
props: {
user,
},
};
} catch (error) {
console.error('Error fetching user profile:', error);
return {
props: {
user: null,
},
};
}
}
export default ProfilePage;