Optimizing data cache reads in your Next.js App Router application while maintaining Server-Side Rendering (SSR) for products can significantly enhance performance and reduce resource consumption. Here's a comprehensive approach to achieve this:
1. Leverage Next.js Built-in Fetch Caching
Instead of using unstable_cache, it's recommended to utilize Next.js's built-in caching mechanisms provided directly through the fetch API. This ensures better integration with Next.js's rendering pipeline and optimized cache management.
Updated Fetch Functions:
const REVALIDATE_SUBBRANDS = 14400; // 4 hours
const REVALIDATE_PRODUCTS = 14400; // 4 hours
const fetchSubBrands = async () => {
const response = await fetch('https://api.naayiq.com/subcategories/brands', {
headers: { 'Content-Type': 'application/json' },
next: { revalidate: REVALIDATE_SUBBRANDS },
// Optionally, specify cache options
cache: 'force-cache', // Ensures the response is cached
});
if (response.status === 200) {
return response.json();
}
throw new Error(`Failed to fetch sub-brands: ${response.statusText}`);
};
const fetchProducts = async () => {
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
next: { revalidate: REVALIDATE_PRODUCTS },
cache: 'force-cache',
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
Benefits:
- Integration: Utilizes Next.js's internal caching, ensuring better compatibility and optimized performance.
- Simplicity: Eliminates the need for wrapping functions with
unstable_cache.
2. Optimize Data Fetching Patterns
Ensure that data fetching functions are called optimally to prevent unnecessary cache reads:
- Single Responsibility: Each fetch function should handle specific data fetching without overlapping responsibilities.
- Avoid Redundant Calls: Ensure that
fetchSubBrands and fetchProducts are not invoked multiple times within the same rendering cycle unless necessary.
Example Optimization:
const getFilteredProducts = async (
page = 1,
query = '',
c = '',
sc = '',
b = '',
minPriceA = 0,
maxPriceA = Infinity,
availability = 'all',
sortBy = ''
) => {
// Initiate both fetches concurrently
const [productsData, subBrands] = await Promise.all([
fetchProducts(), // Cached fetch
b ? fetchSubBrands() : Promise.resolve([]), // Conditional cached fetch
]);
// ... rest of your filtering logic
};
Benefits:
- Concurrency: Fetches data concurrently, reducing overall waiting time.
- Conditional Fetching: Only fetches
subBrands when necessary, minimizing unnecessary cache reads.
3. Reduce Data Payloads
Minimize the amount of data being fetched and cached by requesting only the necessary fields. This reduces the memory footprint and speeds up data retrieval.
Example:
If your API supports it, modify the fetch requests to include query parameters that limit the fields:
const fetchProducts = async () => {
const response = await fetch('https://api.naayiq.com/products?fields=id,name,price,sold', {
headers: { 'Content-Type': 'application/json' },
next: { revalidate: REVALIDATE_PRODUCTS },
cache: 'force-cache',
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
Benefits:
- Efficiency: Reduces the size of the data being processed and cached.
- Performance: Speeds up data transfer and processing times.
4. Implement Incremental Static Regeneration (ISR) Smartly
Since you're already using a revalidate period of 4 hours (14400 seconds), ensure that this interval aligns with your application's data freshness requirements. ISR allows pages to be updated after the initial build without requiring a full rebuild.
Considerations:
- Data Volatility: If your product data doesn't change frequently, a longer
revalidate period is beneficial.
- User Experience: Balance between data freshness and performance to provide the best user experience.
5. Monitor and Analyze Cache Performance
Use Vercel's analytics and monitoring tools to gain insights into cache performance. Understanding cache hit/miss ratios can help you further optimize caching strategies.
Steps:
- Enable Analytics: Ensure that Vercel's analytics are enabled for your project.
- Review Metrics: Look for patterns in cache usage, identify high cache read areas, and adjust strategies accordingly.
- Optimize Based on Insights: Modify caching strategies based on observed data.
6. Handle Errors Gracefully
Ensure that your application can handle fetch errors gracefully without causing excessive cache reads due to repeated failures.
Example:
const fetchProducts = async () => {
try {
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
next: { revalidate: REVALIDATE_PRODUCTS },
cache: 'force-cache',
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
} catch (error) {
console.error(error);
// Optionally, implement retry logic or fallback data
return { products: [] };
}
};
Benefits:
- Resilience: Prevents the application from breaking due to fetch failures.
- Stability: Reduces the chances of excessive cache reads caused by repeated fetch attempts.
7. Consider Edge Caching for Static Assets
For assets that don't change frequently, leverage Edge Caching by setting appropriate cache headers. This offloads caching responsibilities to the edge, reducing load on your server.
Example:
In your next.config.js:
module.exports = {
async headers() {
return [
{
source: '/static/:path*',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=31536000, immutable',
},
],
},
];
},
};
Benefits:
- Performance: Faster asset delivery from edge locations.
- Efficiency: Reduces server load and cache reads.
8. Final Revised ProductsPage Component
Here's how your ProductsPage component can look after implementing the above optimizations:
import React from 'react';
import ProductList from '@/components/ProductList';
import AsyncNavBar from '@/components/AsyncNavBar';
const ITEMS_PER_PAGE = 15;
export const revalidate = 14400; // 4 hours
const REVALIDATE_SUBBRANDS = 14400; // 4 hours
const REVALIDATE_PRODUCTS = 14400; // 4 hours
const fetchSubBrands = async () => {
const response = await fetch('https://api.naayiq.com/subcategories/brands', {
headers: { 'Content-Type': 'application/json' },
next: { revalidate: REVALIDATE_SUBBRANDS },
cache: 'force-cache',
});
if (response.status === 200) {
return response.json();
}
throw new Error(`Failed to fetch sub-brands: ${response.statusText}`);
};
const fetchProducts = async () => {
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
next: { revalidate: REVALIDATE_PRODUCTS },
cache: 'force-cache',
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
const getFilteredProducts = async (
page = 1,
query = '',
c = '',
sc = '',
b = '',
minPriceA = 0,
maxPriceA = Infinity,
availability = 'all',
sortBy = ''
) => {
let [productsData, subBrands] = await Promise.all([
fetchProducts(),
b ? fetchSubBrands() : Promise.resolve([]),
]);
let products = productsData.products;
const subCategories = b
? subBrands
.filter((item) => item.category_id.toString() === b)
.map((item) => item.id.toString())
: [];
// Calculate min and max prices
let minPrice = Infinity;
let maxPrice = -Infinity;
products.forEach(product => {
product.sizes.forEach(size => {
const price = parseFloat(size.price);
if (price < minPrice) minPrice = price;
if (price > maxPrice) maxPrice = price;
});
});
const filterProduct = (product) => {
if (
c &&
!product.categories.some(
(cat) => cat.main_category_id?.toString() === c
)
)
return false;
if (
sc &&
product?.brand_id.toString() !== sc &&
!product.categories.some((cat) => cat.id?.toString() === sc)
)
return false;
if (
b &&
!subCategories.includes(product?.brand_id.toString())
)
return false;
// Price range filter
const productPrices = product.sizes.map(size => parseFloat(size.price));
const productMinPrice = Math.min(...productPrices);
const productMaxPrice = Math.max(...productPrices);
if (productMinPrice < minPriceA || productMaxPrice > maxPriceA) {
return false;
}
if (availability !== 'all') {
const inStock = product.sizes.some(size => size.qty > 0);
if (
(availability === 'in_stock' && !inStock) ||
(availability === 'out_of_stock' && inStock)
) {
return false;
}
}
if (query) {
const normalizedName = product.name
.normalize('NFC')
.toLowerCase();
const cleanName = normalizedName.replace(
/[\u200E\u200F\u202A-\u202E\u2066-\u2069]/g,
''
);
const queryWords = query.toLowerCase().split(/\s+/);
return queryWords.every((word) => cleanName.includes(word));
}
return true;
};
// Apply the filter
let filteredProducts = products.filter(filterProduct);
// Calculate total sold for each product
filteredProducts.forEach(product => {
product.totalSold = product.sizes.reduce((sum, size) => sum + size.sold, 0);
});
// Apply sorting
switch (sortBy) {
case 'Price: Low to High':
filteredProducts.sort((a, b) => Math.min(...a.sizes.map(s => parseFloat(s.price))) - Math.min(...b.sizes.map(s => parseFloat(s.price))));
break;
case 'Price: High to Low':
filteredProducts.sort((a, b) => Math.max(...b.sizes.map(s => parseFloat(s.price))) - Math.max(...a.sizes.map(s => parseFloat(s.price))));
break;
case 'Name: A to Z':
filteredProducts.sort((a, b) => a.name.localeCompare(b.name));
break;
case 'Name: Z to A':
filteredProducts.sort((a, b) => b.name.localeCompare(a.name));
break;
case 'Best Selling':
filteredProducts.sort((a, b) => b.totalSold - a.totalSold);
break;
case 'Newest Arrivals':
filteredProducts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
break;
default:
// Default sorting (optional)
break;
}
if (query && !sortBy) {
const lowerQuery = query.toLowerCase();
filteredProducts.sort((a, b) => {
const aIndex = a.name.toLowerCase().indexOf(lowerQuery);
const bIndex = b.name.toLowerCase().indexOf(lowerQuery);
return (
(aIndex === -1 ? Infinity : aIndex) -
(bIndex === -1 ? Infinity : bIndex)
);
});
}
const totalProducts = filteredProducts.length;
const start = 0;
const end = page * ITEMS_PER_PAGE;
return {
products: filteredProducts.slice(start, end),
totalProducts,
hasMore: end < totalProducts,
minPrice,
maxPrice,
};
};
// The main ProductsPage component
const ProductsPage = async ({ searchParams }) => {
const page = parseInt(searchParams.page) || 1;
const query = searchParams.query || '';
const c = searchParams.c || '';
const sc = searchParams.sc || '';
const b = searchParams.b || '';
const minPriceF = parseFloat(searchParams.minPrice) || 0;
const maxPriceF = parseFloat(searchParams.maxPrice) || Infinity;
const availability = searchParams.availability || 'all';
const sortBy = searchParams.sortBy || '';
const title = searchParams.title || '';
try {
const { products, totalProducts, hasMore, minPrice, maxPrice } = await getFilteredProducts(
page,
query,
c,
sc,
b,
minPriceF,
maxPriceF,
availability,
sortBy
);
return (
<>
<AsyncNavBar />
<ProductList
initialProducts={products}
totalProducts={totalProducts}
hasMore={hasMore}
initialPage={page}
initialQuery={query}
initialC={c}
initialSc={sc}
initialB={b}
minPrice={minPrice}
maxPrice={maxPrice}
title={sortBy || title || "All Products"}
/>
</>
);
} catch (error) {
console.error(error);
return <div>Error: {error.message}</div>;
}
};
export default ProductsPage;
9. Additional Recommendations
-
Edge Functions: Consider moving data fetching to Edge Functions if you require lower latency and closer proximity to your users.
-
Pagination Optimization: Implement cursor-based pagination instead of offset-based to enhance performance for large datasets.
-
Selective Revalidation: If certain parts of your data change more frequently, adjust their revalidate intervals accordingly to optimize cache freshness and read efficiency.
10. Conclusion
By transitioning from unstable_cache to Next.js's integrated fetch caching, optimizing your data fetching patterns, reducing data payloads, and leveraging ISR effectively, you can significantly reduce data cache reads and enhance the performance of your SSR application. Monitor your application's performance continuously and adjust your strategies based on real-world usage and data to maintain optimal performance.