getServerSideProps
The getServerSideProps function is Next.js's way of implementing server-side rendering. It runs on every request and fetches data that your page needs before rendering.
Think of it as a pre-flight checklist. Before the page is sent to the user, this function gathers all the necessary data, ensuring the page is complete and ready to display.
How It Works
When a user requests a page, Next.js runs getServerSideProps on the server. This function can fetch data from databases, APIs, or any other source.
// app/dashboard/page.js
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
const userData = await getUserData(session.user.id);
return {
props: {
user: userData,
},
};
}
The function receives a context object containing the request, response, query parameters, and other useful information.
The Context Object
The context object provides everything you need to understand the current request:
export async function getServerSideProps(context) {
const { req, res, query, params } = context;
// Access request headers
const userAgent = req.headers['user-agent'];
// Access cookies
const cookies = req.cookies;
// Access query parameters
const page = query.page || 1;
// Access route parameters (for dynamic routes)
const id = params.id;
return { props: { userAgent, page } };
}
This information lets you customize the response based on the user's request.
Redirects and 404s
You can handle redirects and not-found pages directly in getServerSideProps:
export async function getServerSideProps(context) {
const post = await getPost(context.params.slug);
if (!post) {
return {
notFound: true,
};
}
if (post.draft) {
return {
redirect: {
destination: '/posts',
permanent: false,
},
};
}
return {
props: { post },
};
}
Returning { notFound: true } shows your custom 404 page. Redirects can be permanent or temporary.
Performance Considerations
While getServerSideProps is powerful, it has performance implications. Since it runs on every request, it can slow down your application if not used carefully.
Consider using getStaticProps with ISR for content that doesn't change on every request. Reserve getServerSideProps for truly dynamic, personalized content.
You can also optimize by implementing caching strategies within your data fetching functions. Cache API responses or database queries when appropriate.