Reducing the data cache size on Vercel when using Next.js App Router involves optimizing your data fetching and caching strategies. Here are several steps and best practices you can follow to achieve this:
1. Optimize Fetch Caching Strategies
a. Use Explicit Cache Control:
Instead of solely relying on revalidate, you can explicitly control caching behavior using the cache option in the fetch function. This helps in managing how and when data is cached.
cache: 'force-cache': Caches the response indefinitely until it is revalidated.
cache: 'no-store': Bypasses the cache entirely and always fetches fresh data.
Example:
const fetchSubBrands = async () => {
const response = await fetch('https://api.naayiq.com/subcategories/brands', {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache', // Use force-cache to cache until revalidate
next: { revalidate: REVALIDATE_SUBBRANDS }, // Revalidate every 4 hours
});
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' },
cache: 'force-cache', // Use force-cache to cache until revalidate
next: { revalidate: REVALIDATE_PRODUCTS }, // Revalidate every 4 hours
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
b. Use unstable_cache for Granular Control (Experimental):
If you need more granular control over caching, unstable_cache can be used. However, it's an experimental feature and should be used with caution.
Example:
import { unstable_cache } from 'next/cache';
const fetchProducts = unstable_cache(async () => {
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
}, { revalidate: REVALIDATE_PRODUCTS });
2. Combine Data Fetching Where Possible
Reducing the number of separate fetch requests can significantly decrease cache size. If your API allows, combine multiple data-fetching operations into a single request.
Example:
const fetchAllData = async () => {
const response = await fetch('https://api.naayiq.com/all-data', {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: 14400 },
});
if (!response.ok) {
throw new Error('Failed to fetch all data');
}
return response.json();
};
// Usage in ProductsPage
const ProductsPage = async ({ searchParams }) => {
try {
const { products, subBrands } = await fetchAllData();
// ... rest of your logic
} catch (error) {
return <div>Error: {error.message}</div>;
}
};
Ensure your backend supports combined endpoints if you choose this approach.
3. Limit Data Size
a. Fetch Only Necessary Fields:
Ensure that your API endpoints return only the fields required for rendering the page. This reduces the payload size and, consequently, the cache size.
Example:
const fetchProducts = async () => {
const response = await fetch('https://api.naayiq.com/products?fields=id,name,price,qty,sold,created_at', {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: REVALIDATE_PRODUCTS },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
b. Implement Server-side Pagination:
Fetch only the required number of items per request rather than fetching all products and then paginating on the server. This can significantly reduce the amount of data being cached.
Example:
const fetchProducts = async (page = 1, limit = ITEMS_PER_PAGE) => {
const response = await fetch(`https://api.naayiq.com/products?page=${page}&limit=${limit}`, {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: REVALIDATE_PRODUCTS },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
4. Implement Server-Side Caching with External Services
Using an external caching service like Redis can offload caching responsibilities from Vercel, helping to manage cache size more effectively.
Steps:
-
Set Up Redis:
-
Integrate Redis in Next.js:
- Install a Redis client like
ioredis or redis.
- Modify your fetch functions to first check Redis before making external API calls.
Example with ioredis:
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
const fetchProducts = async () => {
const cachedProducts = await redis.get('products');
if (cachedProducts) {
return JSON.parse(cachedProducts);
}
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
const products = await response.json();
await redis.set('products', JSON.stringify(products), 'EX', REVALIDATE_PRODUCTS);
return products;
};
5. Normalize and Reduce Cache Key Variations
Ensure that your fetch requests use consistent URLs and parameters to prevent creating numerous cache entries.
a. Normalize Query Parameters:
Sort query parameters in a consistent order to avoid cache misses due to different parameter sequences.
Example:
const normalizeQuery = (params) => {
const sortedKeys = Object.keys(params).sort();
return sortedKeys.map(key => `${key}=${params[key]}`).join('&');
};
const fetchProducts = async (params) => {
const queryString = normalizeQuery(params);
const url = `https://api.naayiq.com/products?${queryString}`;
const response = await fetch(url, {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: REVALIDATE_PRODUCTS },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
};
b. Limit Dynamic Parameters:
Avoid using highly dynamic parameters that create unique cache keys unnecessarily. Instead, handle some variations on the client side if feasible.
6. Move Filtering Logic Client-Side
If possible, fetch a manageable amount of data and perform filtering on the client side. This reduces the number of unique server-side cache entries.
Example:
// Fetch all necessary products data client-side using SWR or React Query
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());
const ProductList = ({ initialProducts }) => {
const { data: products, error } = useSWR('https://api.naayiq.com/products', fetcher, { initialData: initialProducts });
if (error) return <div>Error loading products.</div>;
if (!products) return <div>Loading...</div>;
// Apply client-side filtering here
const filteredProducts = products.filter(product => {
// Your filter logic
});
return (
// Render filtered products
);
};
Note: This approach is suitable when the data size is manageable on the client side.
7. Monitor and Analyze Cache Usage
Use Vercel’s analytics and monitoring tools to understand cache usage patterns. Identify which endpoints or data are contributing most to the cache size and optimize accordingly.
8. Example Refactored Code Incorporating Some of These Strategies
Here’s how you can refactor parts of your ProductsPage to implement some of the above recommendations:
import React from 'react';
import ProductList from '@/components/ProductList';
import AsyncNavBar from '@/components/AsyncNavBar';
import Redis from 'ioredis';
const ITEMS_PER_PAGE = 15;
const REVALIDATE_TIME = 14400; // 4 hours
const redis = new Redis(process.env.REDIS_URL);
// Fetch products with caching via Redis
const fetchProducts = async () => {
const cached = await redis.get('products');
if (cached) {
return JSON.parse(cached);
}
const response = await fetch('https://api.naayiq.com/products', {
headers: { 'Content-Type': 'application/json' },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
const products = await response.json();
await redis.set('products', JSON.stringify(products), 'EX', REVALIDATE_TIME);
return products;
};
// Fetch sub-brands with caching via Redis
const fetchSubBrands = async () => {
const cached = await redis.get('subBrands');
if (cached) {
return JSON.parse(cached);
}
const response = await fetch('https://api.naayiq.com/subcategories/brands', {
headers: { 'Content-Type': 'application/json' },
});
if (response.status === 200) {
const data = await response.json();
await redis.set('subBrands', JSON.stringify(data), 'EX', REVALIDATE_TIME);
return data;
}
throw new Error(`Failed to fetch sub-brands: ${response.statusText}`);
};
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())
: [];
// ... (rest of your filtering logic)
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) {
return <div>Error: {error.message}</div>;
}
};
export default ProductsPage;
9. Additional Best Practices
-
Avoid Over-fetching: Ensure that you’re not fetching more data than necessary. Use selective queries or GraphQL to fetch only required fields.
-
Compression: If possible, compress responses from your APIs to reduce data size.
-
Static Assets: Serve static assets (like images) via a CDN to offload from your Next.js server.
-
Lazy Loading Components: Load components or data only when needed to minimize initial data load and caching.
10. Conclusion
By implementing these strategies, you can significantly reduce the data cache size on Vercel while maintaining efficient data fetching and rendering in your Next.js application. Start by adjusting your caching policies, optimizing data payloads, and leveraging external caching solutions if necessary. Monitor your cache usage and iteratively refine your approach to find the optimal balance between performance and cache size.
If you have specific constraints or additional questions, feel free to provide more details!