I'm using nextjs app router with vercel serverless... I want to you to optimize the…
- User
I'm using nextjs app router with vercel serverless... I want to you to optimize the following and reduce vercel data cache reads... and improve its overall performance... I want to keep the code and all the process in SSR. 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
// Helper function to construct query strings const constructQueryParams = (params) => { const query = new URLSearchParams(); for (const key in params) { if ( params[key] !== '' && params[key] !== undefined && params[key] !== null && !Number.isNaN(params[key]) ) { query.set(key, params[key]); } } return query.toString(); };
// Fetch products with API filtering and caching const fetchProducts = async (params) => { const queryString = constructQueryParams(params); const url = https://api.naayiq.com/products?${queryString};
const response = await fetch(url, { headers: { 'Content-Type': 'application/json' }, // Use Next.js's built-in revalidation and caching cache: 'force-cache', next: { revalidate: REVALIDATE_PRODUCTS }, });
if (!response.ok) { throw new Error('Failed to fetch products'); }
return response.json(); };
// Function to get filtered products const getFilteredProducts = async (params) => { const { page = 1, query = '', c = '', sc = '', b = '', minPriceA = 0, maxPriceA = Infinity, availability = 'all', sortBy = '', } = params;
// Prepare API parameters const apiParams = { page, query, category: c, subCategory: sc, brand: b, minPrice: minPriceA, maxPrice: maxPriceA === Infinity ? undefined : maxPriceA, availability, sortBy, limit: ITEMS_PER_PAGE, };
// Generate a cache key based on the parameters const cacheKey = products-${JSON.stringify(apiParams)};
// Fetch products using API filtering and caching const productsData = await fetchProducts(apiParams);
const products = productsData.products || [];
// Calculate min and max prices if needed 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 totalProducts = productsData.total || products.length; const hasMore = page * ITEMS_PER_PAGE < totalProducts;
return { products, totalProducts, hasMore, minPrice, maxPrice, }; };
// The main ProductsPage component const ProductsPage = async ({ searchParams }) => { const { page = '1', query = '', c = '', sc = '', b = '', minPrice = '0', maxPrice = '', availability = 'all', sortBy = '', title = '', } = searchParams;
- Assistant