In serverless environments like Vercel, using in-memory caches (such as unstable_cache) can lead to increased resource consumption and potential performance issues because serverless functions are ephemeral and do not maintain state between invocations. Instead, it's more efficient to leverage HTTP caching strategies and utilize Vercel's edge caching capabilities.
Here's how you can refactor your code to use fetch with appropriate caching options instead of unstable_cache:
-
Use fetch with Caching Options:
Next.js provides advanced caching capabilities through the fetch API. You can control caching behavior using the cache and next options. This approach leverages Vercel's CDN to cache your responses effectively.
-
Set Revalidation Intervals:
Define how often the cached data should be revalidated to ensure that your application serves fresh content without overloading your server.
-
Update Your Data Fetching Functions:
Replace the unstable_cache with fetch calls that include the caching options.
Updated Code Example
import React from 'react';
import ProductList from '@/components/ProductList';
import AsyncNavBar from '@/components/AsyncNavBar';
export const runtime = 'edge';
const ITEMS_PER_PAGE = 15;
// Fetch sub-brands with caching
const fetchSubBrands = async () => {
const response = await fetch('https://api.naayiq.com/subcategories/brands', {
headers: { 'Content-Type': 'application/json' },
// Use 'force-cache' to cache the response at the CDN level
// 'next' options allow you to set revalidation time
cache: 'force-cache',
next: { revalidate: 60 }, // Revalidate every 60 seconds
});
if (response.status === 200) {
return await response.json();
}
throw new Error(response.statusText);
};
// Fetch products with caching
const fetchProducts = async () => {
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: 60 }, // Revalidate every 60 seconds
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
async function getFilteredProducts(page = 1, query = '', c = '', sc = '', b = '') {
// Use Promise.all to fetch data concurrently
const [products, subBrands] = await Promise.all([
fetchProducts(),
b ? fetchSubBrands() : [{}],
]);
const subCategories = b
? subBrands
.filter((item) => item.category_id.toString() === b)
.map((item) => item.id.toString())
: null;
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.some((b_id) => b_id === product?.brand_id.toString())
)
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;
};
let filteredProducts = products.filter(filterProduct);
if (query) {
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; // Always start from the first product
const end = page * ITEMS_PER_PAGE; // Get all products up to the current page
return {
products: filteredProducts.slice(start, end),
totalProducts,
hasMore: end < totalProducts,
};
}
async function ProductsPage({ searchParams }) {
const page = parseInt(searchParams.page) || 1;
const query = searchParams.query || '';
const c = searchParams.c || '';
const sc = searchParams.sc || '';
const b = searchParams.b || '';
try {
const { products, totalProducts, hasMore } = await getFilteredProducts(
page,
query,
c,
sc,
b
);
return (
<>
<AsyncNavBar />
<ProductList
initialProducts={products}
totalProducts={totalProducts}
hasMore={hasMore}
initialPage={page}
initialQuery={query}
initialC={c}
initialSc={sc}
/>
</>
);
} catch (error) {
// Handle errors gracefully
return <div>Error: {error.message}</div>;
}
}
export default ProductsPage;
Explanation of Changes
-
Removed unstable_cache:
The unstable_cache has been removed to prevent potential resource overhead in a serverless environment.
-
Implemented fetch with Caching Options:
cache: 'force-cache': This option tells the fetch to cache the response at the CDN level (Vercel Edge).
next: { revalidate: 60 }: This sets the revalidation time to 60 seconds. After 60 seconds, the cached response will be revalidated by fetching fresh data from the origin.
-
Error Handling:
Added a try-catch block in the ProductsPage component to handle any potential errors gracefully.
-
Concurrency with Promise.all:
The fetchProducts and fetchSubBrands functions are called concurrently to optimize performance.
Benefits of This Approach
-
Efficient Resource Usage: By leveraging CDN caching, you reduce the load on your serverless functions, leading to better performance and lower costs.
-
Scalability: CDNs like Vercel's Edge Network are designed to handle high traffic efficiently, ensuring that your application scales seamlessly.
-
Improved Response Times: Serving cached responses from the CDN can significantly reduce latency, enhancing the user experience.
Additional Recommendations
-
Adjust Revalidation Time: Depending on how frequently your data changes, you might want to adjust the revalidate interval to balance freshness and performance.
-
Use Incremental Static Regeneration (ISR): For pages that don't need to be entirely dynamic, consider using ISR to statically generate pages and update them in the background.
-
Leverage Vercel's Built-in Caching: Ensure that your deployment on Vercel is configured to take full advantage of their caching strategies. Review Vercel's caching documentation for more details.
By adopting these strategies, you can optimize your Next.js application for serverless environments like Vercel, ensuring efficient resource usage and optimal performance.