Mastering SSR in Next.js: A Guide to Caching Series Part Two

👨💻 Frontend Advocate | Tech Blogger | Dedicated to creating intuitive user experiences and optimizing web performance with ReactJS and Next.js. Let’s innovate and build exceptional applications together! 🚀
Server-Side Rendering (SSR) is a robust feature of Next.js that enables pre-rendering of pages for each request, leading to dynamic content delivery and enhanced speed. Implementing SSR with caching can significantly reduce server load and improve response times, thereby enhancing the user experience. In this article, we will explore SSR with caching in Next.js, covering key concepts, benefits, and practical applications.
Understanding Server-Side Rendering (SSR)
With Next.js, you can pre-render pages on each request using a feature called Server-Side Rendering (SSR), which enables dynamic content delivery with improved performance. By combining SSR with caching, you can significantly reduce server load and speed up response times, enhancing the user experience. In this blog, we'll delve into SSR with caching in Next.js, covering important concepts, benefits, and practical applications.
How SSR Works in Next.js
When a request is made to a Next.js application, the server fetches the necessary data, renders the page, and sends the HTML to the client. This process happens for every request, ensuring that the content is always up-to-date.
Benefits of SSR with Caching
Improved Performance: By caching the server-rendered pages, you reduce the need for repeated data fetching and rendering, leading to faster response times.
Reduced Server Load: Caching allows you to serve content from the cache instead of processing every request on the server, easing the load on your backend.
SEO Optimization: Pre-rendered pages improve crawlability and indexing by search engines, enhancing your site's SEO performance.
Implementing SSR with Caching in Next.js
Setting Up SSR in Next.js
First, let's set up a basic SSR implementation in Next.js:
// pages/product/[id].js
export async function getServerSideProps({ params }) {
const res = await fetch(`https://api.example.com/blogs/${params.id}`);
const blog = await res.json();
return {
props: {
blog,
},
};
}
const BlogPage = ({ blog }) => (
<div>
<h1>{blog.title}</h1>
<p>{blog.content}</p>
</div>
);
export default BlogPage;
In this example, getServerSideProps fetches product data from an API for each request, rendering the product page dynamically.
Adding Caching Headers
To cache the server-rendered pages, you can set HTTP caching headers in the response. The Cache-Control header lets you decide how long the content should be cached.
// pages/product/[id].js
export async function getServerSideProps({ params, res }) {
const res = await fetch(`https://api.example.com/blogs/${params.id}`);
const blog = await res.json();
res.setHeader('Cache-Control', 's-maxage=10, stale-while-revalidate=60');
return {
props: {
blog,
},
};
}
const BlogPage = ({ blog }) => (
<div>
<h1>{blog.title}</h1>
<p>{blog.content}</p>
</div>
);
export default BlogPage;
In this code, s-maxage specifies the time (in seconds) that the response is considered fresh, while stale-while-revalidate allows serving stale content while revalidating in the background.
Example of SSR Caching
Caching API Responses
By caching API responses, you can serve content quickly without waiting for the server to fetch data from the API repeatedly.
let cache = {};
export async function getServerSideProps({ params }) {
const cachedData = cache[params.id];
if (cachedData) {
return { props: { blog: cachedData } };
}
const res = await fetch(`https://api.example.com/blogs/${params.id}`);
const blog = await res.json();
cache[params.id] = blog;
return {
props: {
blog,
},
};
}
const BlogPage = ({ blog }) => (
<div>
<h1>{blog.title}</h1>
<p>{blog.content}</p>
</div>
);
export default BlogPage;
Using Edge Caching with Vercel
Vercel, the company behind Next.js, provides built-in support for edge caching, allowing you to cache responses at the edge for faster global delivery.
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/blog/:id',
headers: [
{
key: 'Cache-Control',
value: 's-maxage=10, stale-while-revalidate=60',
},
],
},
];
},
};
This configuration sets the cache headers for the /blog/:id route, enabling edge caching for server-rendered pages.
Best Practices for SSR Caching in Next.js
Set Appropriate Cache Times: Balance cache freshness and performance by setting suitable
s-maxageandstale-while-revalidatevalues.Monitor Cache Performance: Regularly monitor your caching strategy to ensure it meets your performance goals and adjust as needed.
Leverage Edge Caching: Use platforms like Vercel for edge caching to deliver content faster to users worldwide.
Conclusion
Implementing SSR with caching in Next.js can significantly boost your app's performance and scalability. By using caching headers, API response caching, and edge caching, you can lower server load, speed up response times, and improve the user experience. Stay tuned for the next & last part of our three-part series, where we will dive into Incremental Static Regeneration (ISR).



