To transition your application from server-side rendering (SSR) to client-side rendering (CSR) while moving all filtering and search logic to the backend, implementing caching, and optimizing for your new VPS environment, follow the comprehensive steps below. This guide covers:
-
Backend Enhancements:
- Move Filtering and Search Logic to the Backend
- Implement Caching with
node-cache
- Optimize for Express 5 and Your VPS
-
Frontend Adjustments:
- Transition to Client-Side Rendering
- Update API Interaction
-
Additional Optimizations
Let's go through each of these steps in detail.
1. Backend Enhancements
1.1. Move Filtering and Search Logic to the Backend
Currently, your frontend fetches all products and then performs filtering. To optimize performance, especially with large datasets, it's best to handle filtering, searching, pagination, and sorting on the backend. This reduces the amount of data transferred and leverages the database's optimized querying capabilities.
Updated getProducts Controller:
// controllers/productController.ts
import { Request, Response } from 'express';
import db from '../db';
import NodeCache from 'node-cache';
const cache = new NodeCache({ stdTTL: 3600 }); // Cache TTL set to 1 hour
export const getProducts = async (req: Request, res: Response) => {
try {
const {
search = '',
c = '',
sc = '',
b = '',
minPrice = '0',
maxPrice = 'Infinity',
availability = 'all',
sortBy = '',
page = '1',
itemsPerPage = '15',
} = req.query;
// Parse and sanitize input
const pageNum = parseInt(page as string, 10) || 1;
const items = parseInt(itemsPerPage as string, 10) || 15;
const minPriceNum = parseFloat(minPrice as string) || 0;
const maxPriceNum = parseFloat(maxPrice as string) < Infinity ? parseFloat(maxPrice as string) : Infinity;
// Generate a unique cache key based on query parameters
const cacheKey = `products:${JSON.stringify(req.query)}`;
// Check if response is cached
if (cache.has(cacheKey)) {
return res.json(cache.get(cacheKey));
}
// Build SQL query with filtering, searching, sorting, and pagination
const queryParams: any[] = [];
const conditions: string[] = [];
// Search filtering
if (search) {
const searchTerm = `%${(search as string).toLowerCase()}%`;
queryParams.push(searchTerm);
conditions.push(`LOWER(p.name) LIKE $${queryParams.length}`);
}
// Category filtering
if (c) {
queryParams.push(c);
conditions.push(`c.id = $${queryParams.length}`);
}
// Subcategory filtering
if (sc) {
queryParams.push(sc);
conditions.push(`sc.id = $${queryParams.length}`);
}
// Brand filtering
if (b) {
queryParams.push(b);
conditions.push(`p.brand_id = $${queryParams.length}`);
}
// Price filtering
queryParams.push(minPriceNum, maxPriceNum);
conditions.push(`s.price BETWEEN $${queryParams.length - 1} AND $${queryParams.length}`);
// Availability filtering
if (availability === 'in_stock') {
conditions.push(`s.qty > 0`);
} else if (availability === 'out_of_stock') {
conditions.push(`s.qty = 0`);
}
// Construct WHERE clause
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
// Sorting
let orderClause = 'ORDER BY p.created_at DESC';
switch (sortBy) {
case 'Price: Low to High':
orderClause = 'ORDER BY s.price ASC';
break;
case 'Price: High to Low':
orderClause = 'ORDER BY s.price DESC';
break;
case 'Name: A to Z':
orderClause = 'ORDER BY p.name ASC';
break;
case 'Name: Z to A':
orderClause = 'ORDER BY p.name DESC';
break;
case 'Best Selling':
orderClause = 'ORDER BY p.sold DESC';
break;
case 'Newest Arrivals':
orderClause = 'ORDER BY p.created_at DESC';
break;
default:
break;
}
// Pagination
const offset = (pageNum - 1) * items;
queryParams.push(items, offset);
const limitClause = `LIMIT $${queryParams.length - 1} OFFSET $${queryParams.length}`;
// Final SQL Query
const productQuery = `
SELECT
p.*,
sc.id AS subcategory_id,
sc.name AS subcategory_name,
c.id AS main_category_id,
c.name AS main_category_name,
s.id AS size_id,
s.name AS size_name,
s.price AS size_price,
s.qty AS size_qty,
s.sold AS size_sold
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN subcategories sc ON pc.category_id = sc.id
LEFT JOIN categories c ON sc.category_id = c.id
LEFT JOIN sizes s ON p.id = s.product_id
${whereClause}
${orderClause}
${limitClause}
`;
const productResult = await db.query(productQuery, queryParams);
// Transforming the data as needed
const products = productResult.rows.map((product) => ({
id: product.id,
name: product.name,
description: product.description,
brand_id: product.brand_id,
has_color: product.has_color,
has_size: product.has_size,
product_type: product.product_type,
price: product.price,
qty: product.qty,
sold: product.sold,
created_at: product.created_at,
updated_at: product.updated_at,
categories: [
{
id: product.subcategory_id,
name: product.subcategory_name,
main_category_id: product.main_category_id,
main_category_name: product.main_category_name,
},
],
sizes: [
{
id: product.size_id,
name: product.size_name,
price: product.size_price,
qty: product.size_qty,
sold: product.size_sold,
},
],
// Include colors and images as needed
}));
// Calculate total products (for pagination)
const countQuery = `
SELECT COUNT(DISTINCT p.id) as total
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN subcategories sc ON pc.category_id = sc.id
LEFT JOIN categories c ON sc.category_id = c.id
LEFT JOIN sizes s ON p.id = s.product_id
${whereClause}
`;
const countResult = await db.query(countQuery, queryParams.slice(0, queryParams.length - 2)); // Exclude LIMIT and OFFSET
const totalProducts = parseInt(countResult.rows[0].total, 10);
const response = {
products,
total: totalProducts,
page: pageNum,
itemsPerPage: items,
totalPages: Math.ceil(totalProducts / items),
};
// Cache the response
cache.set(cacheKey, response);
res.json(response);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Key Changes:
-
Query Parameters Handling: Receives all filter, search, sort, and pagination parameters via req.query.
-
Caching: Utilizes node-cache to cache responses based on query parameters. This reduces database load for frequently requested data.
-
Optimized SQL Query: The SQL query now includes filtering, searching, sorting, and pagination directly within the database layer, leveraging SQL's efficiency.
-
Pagination: Added LIMIT and OFFSET to handle pagination.
-
Total Count: Performs a separate count query to determine the total number of products matching the criteria, facilitating frontend pagination controls.
-
Error Handling: Enhanced error handling to ensure any issues are logged and appropriate responses are sent.
1.2. Implement Caching with node-cache
Caching frequently accessed data can significantly improve performance, especially for endpoints with expensive database queries.
Setup node-cache:
npm install node-cache
Implement Caching in getProducts:
As shown in the getProducts controller above, node-cache is initialized with a TTL (Time To Live) of 1 hour. The cache key is generated based on the serialized query parameters to ensure uniqueness for different queries.
Example Caching Implementation:
import NodeCache from 'node-cache';
const cache = new NodeCache({ stdTTL: 3600 }); // 1 hour TTL
// Inside your controller
const cacheKey = `products:${JSON.stringify(req.query)}`;
if (cache.has(cacheKey)) {
return res.json(cache.get(cacheKey));
}
// After fetching from DB
cache.set(cacheKey, response);
Considerations:
-
Cache Invalidation: Ensure that when products are added, updated, or deleted, related cache entries are invalidated or updated to prevent serving stale data. Implement cache invalidation logic in your product creation/update/delete controllers.
-
Cache Size: Monitor memory usage, especially with a 1GB VPS. node-cache stores data in memory, so ensure that the cache size doesn't grow uncontrollably. You might need to implement eviction policies or use an external caching solution like Redis for better scalability.
1.3. Optimize for Express 5 and Your VPS
With the transition to Express 5, ensure compatibility by adhering to the new API changes.
Update Express Routes:
Replace deprecated methods and signatures as per Express 5 documentation.
Example Route Setup:
// routes/productRoutes.ts
import express from 'express';
import { getProducts } from '../controllers/productController';
import { getAllBrands, getAllNonBrands } from '../controllers/subcategoryController';
const router = express.Router();
router.get('/products', getProducts);
router.get('/subcategories/non-brands', getAllNonBrands);
router.get('/subcategories/brands', getAllBrands);
export default router;
Main Server File Adjustments:
Ensure the main server file uses the updated express.json() and proper error handling.
// server.ts
import express, { Request, Response, NextFunction } from 'express';
import productRoutes from './routes/productRoutes';
import cors from 'cors';
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Routes
app.use('/api', productRoutes);
// 404 Handler
app.use((req: Request, res: Response) => {
res.status(404).json({ message: 'Route not found' });
});
// Error Handler
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
res.status(500).json({ message: 'Internal Server Error' });
});
// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Optimize for a 1GB VPS:
-
Memory Management: With limited memory, ensure that your caching strategy is efficient. Monitor memory usage and consider limiting cache size or using a more memory-efficient caching solution like Redis.
-
Database Connections: Use connection pooling to manage database connections efficiently. Ensure that the number of connections doesn’t exceed what your VPS can handle.
-
Static Assets: Serve static assets (if any) efficiently using middleware like express.static with appropriate caching headers.
2. Frontend Adjustments
Transitioning to client-side rendering involves moving the data fetching logic to the client, typically using hooks like useEffect in React. Here's how you can adjust your Next.js products page.
2.1. Remove Server-Side Rendering Logic
Since the filtering and search logic is now handled by the backend, simplify your frontend by removing server-side data fetching and moving it to the client.
2.2. Update ProductsPage Component for CSR
Updated ProductsPage Component:
// pages/products.tsx
import React, { useState, useEffect } from 'react';
import ProductList from '@/components/ProductList';
import AsyncNavBar from '@/components/AsyncNavBar';
import Link from 'next/link';
const ITEMS_PER_PAGE = 15;
interface Product {
id: string;
name: string;
description: string;
brand_id: string;
has_color: boolean;
has_size: boolean;
product_type: string;
price: number;
qty: number;
sold: number;
created_at: string;
updated_at: string;
categories: {
id: string;
name: string;
main_category_id: string;
main_category_name: string;
}[];
sizes: {
id: string;
name: string;
price: number;
qty: number;
sold: number;
}[];
// Add other relevant fields
}
const ProductsPage: React.FC = () => {
// Define state variables
const [products, setProducts] = useState<Product[]>([]);
const [totalProducts, setTotalProducts] = useState(0);
const [page, setPage] = useState(1);
const [query, setQuery] = useState('');
const [c, setC] = useState('');
const [sc, setSc] = useState('');
const [b, setB] = useState('');
const [minPrice, setMinPrice] = useState(0);
const [maxPrice, setMaxPrice] = useState(Infinity);
const [availability, setAvailability] = useState('all');
const [sortBy, setSortBy] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Function to fetch products
const fetchProducts = async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: page.toString(),
itemsPerPage: ITEMS_PER_PAGE.toString(),
query,
c,
sc,
b,
minPrice: minPrice.toString(),
maxPrice: maxPrice !== Infinity ? maxPrice.toString() : '',
availability,
sortBy,
});
const response = await fetch(`https://api.naayiq.com/api/products?${params.toString()}`, {
headers: { 'Content-Type': 'application/json' },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
const data = await response.json();
setProducts(data.products);
setTotalProducts(data.total);
} catch (err: any) {
console.error('Error fetching products:', err);
setError('Failed to load products. Please try again later.');
} finally {
setLoading(false);
}
};
// Fetch products on component mount and when dependencies change
useEffect(() => {
fetchProducts();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, query, c, sc, b, minPrice, maxPrice, availability, sortBy]);
// Handle pagination, filters, and sorting updates (Implement these handlers as needed)
// Example:
const handlePageChange = (newPage: number) => {
setPage(newPage);
};
// Render component
return (
<>
<AsyncNavBar />
<div className="container mx-auto p-4">
{/* Implement your filters, search, and sorting controls here */}
{loading && <p>Loading products...</p>}
{error && (
<div className="text-red-500">
<p>{error}</p>
<Link href="/" className="text-blue-500 underline mt-2">
Go back home
</Link>
</div>
)}
{!loading && !error && (
<ProductList
products={products}
totalProducts={totalProducts}
currentPage={page}
itemsPerPage={ITEMS_PER_PAGE}
onPageChange={handlePageChange}
// Pass other necessary props for filters and sorting
/>
)}
</div>
</>
);
};
export default ProductsPage;
Key Changes:
-
State Management: Introduced useState hooks to manage filters, sorting, pagination, loading state, and error handling.
-
Data Fetching: Utilizes useEffect to fetch products whenever relevant state variables change.
-
API Interaction: Constructs the API URL with query parameters matching the backend's expected parameters.
-
Error Handling: Displays user-friendly error messages and provides navigation back to the home page if fetching fails.
-
Component Structure: Ensures components like ProductList receive the necessary props to display products and handle pagination.
2.3. Update ProductList Component
Ensure that your ProductList component can handle the new props and display products accordingly.
Example ProductList Component:
// components/ProductList.tsx
import React from 'react';
import Link from 'next/link';
interface ProductListProps {
products: Product[];
totalProducts: number;
currentPage: number;
itemsPerPage: number;
onPageChange: (page: number) => void;
// Add other props like filters, sorting handlers if needed
}
const ProductList: React.FC<ProductListProps> = ({
products,
totalProducts,
currentPage,
itemsPerPage,
onPageChange,
}) => {
const totalPages = Math.ceil(totalProducts / itemsPerPage);
return (
<div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
{products.map((product) => (
<div key={product.id} className="border p-4 rounded">
<Link href={`/products/${product.id}`}>
<a>
<h2 className="text-lg font-bold">{product.name}</h2>
<p>{product.description}</p>
{/* Add more product details as needed */}
</a>
</Link>
</div>
))}
</div>
{/* Pagination Controls */}
<div className="flex justify-center mt-6">
{Array.from({ length: totalPages }, (_, index) => (
<button
key={index + 1}
onClick={() => onPageChange(index + 1)}
className={`mx-1 px-3 py-1 border rounded ${
currentPage === index + 1 ? 'bg-blue-500 text-white' : 'bg-white text-black'
}`}
>
{index + 1}
</button>
))}
</div>
</div>
);
};
export default ProductList;
Key Points:
-
Dynamic Rendering: Renders products dynamically based on the data fetched from the backend.
-
Pagination: Provides pagination controls allowing users to navigate through pages.
-
Styling: Adjust the styling as needed to fit your design preferences.
2.4. Implement Filters and Sorting Controls
Implement UI controls for filters, search, and sorting that update the relevant state variables in ProductsPage.
Example Filters and Sorting:
// Inside ProductsPage component's return statement
<div className="flex flex-wrap mb-4">
{/* Search Bar */}
<input
type="text"
placeholder="Search..."
value={query}
onChange={(e) => setQuery(e.target.value)}
className="border p-2 rounded mr-2"
/>
{/* Category Filter */}
<select value={c} onChange={(e) => setC(e.target.value)} className="border p-2 rounded mr-2">
<option value="">All Categories</option>
{/* Populate with categories fetched from another API or predefined */}
</select>
{/* Subcategory Filter */}
<select value={sc} onChange={(e) => setSc(e.target.value)} className="border p-2 rounded mr-2">
<option value="">All Subcategories</option>
{/* Populate with subcategories */}
</select>
{/* Brand Filter */}
<select value={b} onChange={(e) => setB(e.target.value)} className="border p-2 rounded mr-2">
<option value="">All Brands</option>
{/* Populate with brands */}
</select>
{/* Price Range */}
<input
type="number"
placeholder="Min Price"
value={minPrice}
onChange={(e) => setMinPrice(parseFloat(e.target.value))}
className="border p-2 rounded mr-2"
/>
<input
type="number"
placeholder="Max Price"
value={maxPrice !== Infinity ? maxPrice : ''}
onChange={(e) => setMaxPrice(e.target.value ? parseFloat(e.target.value) : Infinity)}
className="border p-2 rounded mr-2"
/>
{/* Availability Filter */}
<select value={availability} onChange={(e) => setAvailability(e.target.value)} className="border p-2 rounded mr-2">
<option value="all">All</option>
<option value="in_stock">In Stock</option>
<option value="out_of_stock">Out of Stock</option>
</select>
{/* Sorting */}
<select value={sortBy} onChange={(e) => setSortBy(e.target.value)} className="border p-2 rounded">
<option value="">Sort By</option>
<option value="Price: Low to High">Price: Low to High</option>
<option value="Price: High to Low">Price: High to Low</option>
<option value="Name: A to Z">Name: A to Z</option>
<option value="Name: Z to A">Name: Z to A</option>
<option value="Best Selling">Best Selling</option>
<option value="Newest Arrivals">Newest Arrivals</option>
</select>
</div>
Notes:
-
Dynamic Options: Ideally, fetch categories, subcategories, and brands from the backend to populate the filter options dynamically.
-
Debouncing: Implement debounce for the search input to prevent excessive API calls on every keystroke.
-
Accessibility: Ensure that all form controls are accessible and usable with keyboard navigation.
3. Additional Optimizations
3.1. Use Environment Variables for Configuration
Store sensitive data and configuration parameters such as API URLs, cache TTLs, and database credentials in environment variables.
Example .env File:
PORT=5000
DATABASE_URL=postgres://username:password@localhost:5432/yourdb
CACHE_TTL=3600
Usage in Code:
// server.ts or other configuration files
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 5000;
const CACHE_TTL = parseInt(process.env.CACHE_TTL || '3600', 10);
// Use PORT and CACHE_TTL as needed
3.2. Rate Limiting and Security
Implement rate limiting and other security best practices to protect your API and server, especially when exposed to the internet.
Implement Rate Limiting with express-rate-limit:
npm install express-rate-limit
Setup Rate Limiting:
// server.ts
import rateLimit from 'express-rate-limit';
// Apply to all requests
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per window
message: 'Too many requests from this IP, please try again after 15 minutes',
});
app.use(limiter);
3.3. Logging
Implement robust logging to monitor your application's health and debug issues.
Use morgan for HTTP Request Logging:
npm install morgan
Setup morgan:
// server.ts
import morgan from 'morgan';
app.use(morgan('combined')); // Or choose a format that suits your needs
3.4. Optimize Database Indexes
Ensure your database has appropriate indexes on columns used in filtering, searching, and sorting to speed up query execution.
Example SQL for Indexing:
-- Index on product name for faster search
CREATE INDEX idx_products_name ON products (LOWER(name));
-- Index on category_id
CREATE INDEX idx_product_categories_category_id ON product_categories (category_id);
-- Index on brand_id
CREATE INDEX idx_products_brand_id ON products (brand_id);
-- Index on price in sizes
CREATE INDEX idx_sizes_price ON sizes (price);
-- Add other indexes based on query patterns
Note: Analyze your query performance using tools like EXPLAIN and adjust indexes accordingly.
3.5. Use Pagination Libraries (Optional)
Consider using pagination libraries or patterns that efficiently handle large datasets, such as cursor-based pagination, to enhance performance and user experience.
4. Final Checklist
Before deploying your updated application, ensure that you:
-
Test All Filters and Sorting: Verify that all filtering, searching, sorting, and pagination functionalities work as expected.
-
Monitor Performance: Use monitoring tools to keep an eye on server performance, memory usage, and response times.
-
Handle Edge Cases: Ensure that your application gracefully handles scenarios like empty results, invalid query parameters, and server errors.
-
Secure Your API: Implement necessary security measures, including authentication (if applicable), CORS policies, and input validation to prevent attacks like SQL injection.
-
Optimize Assets: If serving images or other static assets, optimize them for faster loading times.
-
Backup Data: Ensure regular backups of your database and any critical data to prevent data loss.
By following these steps, you'll effectively transition your application to client-side rendering with all filtering and search logic handled on the backend, implement efficient caching mechanisms, and optimize your setup for your VPS environment. This architecture enhances performance, scalability, and maintainability, providing a better experience for your users.