To migrate your API integration from using CORS credentials to Bearer tokens and enhance the Wishlist component by displaying product names and their cheapest prices, follow the steps below. Additionally, we'll ensure the design remains smooth, stable, and compatible, especially for Safari users.
1. Backend Adjustments (Optional but Recommended)
Before diving into the frontend changes, it's beneficial to ensure that your backend /wishlist endpoint provides comprehensive product details. This modification will simplify data handling on the frontend.
Current getWishlist Endpoint:
// controllers/wishlistController.ts
export const getWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
try {
const query = `
SELECT p.id
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
`;
const { rows } = await pool.query(query, [userId]);
res.status(200).json({ wishlist: rows });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
Enhanced getWishlist Endpoint:
Modify the SQL query to fetch additional product details such as name, price, and images. This will allow the frontend to display all necessary information without making multiple API calls.
// controllers/wishlistController.ts
export const getWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
try {
const query = `
SELECT p.id, p.name, p.price, p.images
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
`;
const { rows } = await pool.query(query, [userId]);
res.status(200).json({ wishlist: rows });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
Explanation:
- Added Fields: The query now selects
p.name, p.price, and p.images alongside p.id.
- Frontend Simplification: With these details, the frontend can directly display product information without additional data fetching.
2. Frontend Adjustments
a. Handling Bearer Tokens
Replace the usage of credentials: "include" with Bearer tokens in your fetch requests. Ensure the token is securely stored, typically in localStorage or sessionStorage. Here's how to adjust your Wishlist component:
b. Updated Wishlist Component
'use client';
import Image from "next/image";
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { CircleArrowLeft, X } from "lucide-react";
import ShoppingBag from "@/components/ShoppingBag";
import Loading from "@/components/Loading";
// Utility function to get the token (you might have a different implementation)
const getToken = () => {
return typeof window !== 'undefined' ? localStorage.getItem("token") : null;
};
// Utility function to get the cheapest price
const getCheapestPrice = (product) => {
const prices = [
product.price && product.price !== '0.00'
? parseFloat(product.price)
: Infinity,
...(product.sizes?.map((size) => parseFloat(size.price)) || []),
...(product.colors?.flatMap((color) => [
parseFloat(color.price),
...(color.sizes?.map((size) => parseFloat(size.price)) || []),
]) || []),
].filter((price) => !isNaN(price) && isFinite(price));
return prices.length > 0 ? Math.min(...prices) : null;
};
const WishlistItem = ({ id, name, price, imageUrl, onRemove }) => {
const router = useRouter();
const handleShoppingBagClick = () => {
router.push(`/products/${id}`);
};
return (
<div className="bg-white rounded-lg p-4 flex items-stretch space-x-4 mb-4">
<div className="relative w-[30%] min-h-[120px]">
<Image
src={imageUrl}
alt={name}
fill
unoptimized
className="object-cover rounded-md"
/>
</div>
<div className="flex-grow flex flex-col justify-center">
<h3 className="font-serif font-medium text-base text-center">{name}</h3>
<p className="text-sm text-center text-gray-600">
{price !== null ? `${price.toLocaleString()} IQD` : 'Price Unavailable'}
</p>
</div>
<div className="flex flex-col justify-center items-center space-y-2">
<button onClick={() => onRemove(id)} className="p-1">
<X size={24} />
</button>
<button onClick={handleShoppingBagClick} className="bg-[#3B5345] rounded-full p-2">
<ShoppingBag width={24} height={24} />
</button>
</div>
</div>
);
};
export default function Wishlist() {
const router = useRouter();
const [wishlistItems, setWishlistItems] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
// Fetch Wishlist with Bearer Token
const fetchWishlist = async () => {
const token = getToken();
if (!token) {
setError('Authentication token not found. Please log in.');
setIsLoading(false);
return;
}
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_API}/wishlist`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Failed to fetch wishlist');
}
const data = await response.json();
// Assuming data.wishlist is an array of products with id, name, price, images
setWishlistItems(data.wishlist.map(item => ({
id: item.id,
name: item.name,
price: getCheapestPrice(item),
imageUrl: `https://storage.naayiq.com/resources/${item.images[0]}`,
})));
} catch (error) {
console.error('Error fetching wishlist:', error);
setError(error.message || 'An unexpected error occurred');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchWishlist();
}, []);
const handleRemoveItem = async (id) => {
const token = getToken();
if (!token) {
setError('Authentication token not found. Please log in.');
return;
}
// Optimistically remove the item from the UI
const updatedItems = wishlistItems.filter(item => item.id !== id);
setWishlistItems(updatedItems);
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_API}/wishlist/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Failed to delete item from wishlist');
}
// Optionally, you can show a success notification here
} catch (error) {
console.error('Error removing item from wishlist:', error);
setError(error.message || 'An unexpected error occurred while removing the item');
// Revert the optimistic update if the server request fails
fetchWishlist();
}
};
return (
<>
<header className="flex items-center mb-6">
<CircleArrowLeft size={52} strokeWidth={0.7} onClick={router.back} className="p-2 relative z-20 cursor-pointer" />
<h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">
Wishlist
</h1>
</header>
<main className="flex-grow flex flex-col items-center">
{isLoading ? (
<Loading />
) : error ? (
<div className="text-red-500 text-center">{error}</div>
) : wishlistItems.length === 0 ? (
<>
<div className="relative w-full h-[33vh]">
<Image
src="https://storage.naayiq.com/resources/empty_wishlist.gif"
alt="Empty wishlist"
fill
unoptimized
priority
quality={100}
className="object-contain"
/>
</div>
<section>
<p className="font-serif text-3xl text-center mb-2 font-semibold">Wishlist is empty!</p>
<p className="font-serif text-lg text-center leading-none">Tap the Heart Button to start</p>
<p className="font-serif text-lg text-center">saving your favorite items.</p>
<Link href="/" className="min-h-[56px] mt-4 items-center font-serif px-3 ssm:px-6 bg-[#3B5345] flex justify-center text-white text-xl rounded-lg">
Start Browsing
</Link>
</section>
</>
) : (
<div className="w-full max-w-md">
{wishlistItems.map(item => (
<WishlistItem
key={item.id}
id={item.id}
name={item.name}
price={item.price}
imageUrl={item.imageUrl}
onRemove={handleRemoveItem}
/>
))}
</div>
)}
</main>
</>
);
}
Explanation of Changes:
-
Bearer Token Integration:
- Fetching the Token: Created a
getToken utility function to retrieve the token from localStorage.
- Authorization Header: Modified the
fetchWishlist and handleRemoveItem functions to include the Authorization: Bearer {token} header in their fetch requests.
- Error Handling: Added error messages to handle scenarios where the token is missing or invalid.
-
Displaying Product Name and Price:
WishlistItem Component: Enhanced to display both the product name and its cheapest price using the getCheapestPrice function.
- Price Formatting: The price is formatted to include commas for thousands and appended with "IQD".
-
Optimistic UI Updates:
- Removed the
useOptimistic hook for simplicity and used state updates directly. If you have a custom useOptimistic hook, ensure it correctly handles the optimistic updates.
-
Improved User Feedback:
- Error Messages: Display error messages prominently to inform users of any issues.
- Loading State: Use the existing
Loading component to indicate data fetching.
-
Design and Compatibility Enhancements:
- Cursor Pointer: Added
cursor-pointer to the back button for better UX.
- Alt Text Correction: Corrected "Tab Heart Button" to "Tap the Heart Button" for clarity.
- Mobile Compatibility: Ensure that all components are responsive. Tailwind CSS classes like
ssm:px-6 already help, but verify on different devices and browsers, especially Safari.
-
Safeguards for Server Data:
- Image URLs: Constructed
imageUrl safely assuming that item.images is an array. Ensure that item.images exists and has at least one image to prevent undefined errors.
c. Ensuring Browser Compatibility (Especially Safari)
Safari has some unique behaviors and limitations. To ensure compatibility:
-
Fetch API Polyfill: While modern versions of Safari support the Fetch API, older versions might not. Consider using a polyfill like whatwg-fetch if you need to support older Safari versions.
npm install whatwg-fetch --save
Then, import it at the top of your entry file (e.g., pages/_app.js):
import 'whatwg-fetch';
-
ES6 Features: Ensure that your JavaScript is transpiled appropriately. Next.js handles this out of the box, but if you use newer features, verify their compatibility or provide polyfills.
-
CSS Prefixes: Tailwind CSS generally handles vendor prefixes, but if you use custom CSS, consider using Autoprefixer to add necessary prefixes for Safari.
-
Testing on Safari: Regularly test your application on Safari (both desktop and mobile) to identify and fix any browser-specific issues.
d. Optimizing Image Loading for Performance
To enhance the smoothness and stability of your application, especially on Safari:
-
Use Next.js Image Optimization:
- Ensure that your
next.config.js includes the appropriate domains.
// next.config.js
module.exports = {
images: {
domains: ['storage.naayiq.com'],
},
};
-
Lazy Loading Images:
- The
Image component in Next.js supports lazy loading by default. Ensure it's properly utilized to improve performance.
-
Placeholder Blur:
- For better UX, consider using a low-quality image placeholder (LQIP) to display blurred images before the actual image loads.
<Image
src={imageUrl}
alt={name}
fill
unoptimized
className="object-cover rounded-md"
placeholder="blur"
blurDataURL="/path-to-blur-image.jpg" // Replace with actual blur data URL or base64
/>
e. Accessibility Enhancements
Ensure that your application is accessible to all users, including those using Safari with VoiceOver or other assistive technologies.
-
Accessible Alt Text:
- Provide meaningful
alt text for all images.
-
Keyboard Navigation:
- Ensure that all interactive elements (buttons, links) are focusable and operable via the keyboard.
-
ARIA Attributes:
- Use ARIA attributes where necessary to improve the semantic structure and accessibility.
<button
onClick={() => onRemove(id)}
className="p-1"
aria-label={`Remove ${name} from wishlist`}
>
<X size={24} />
</button>
3. Complete Code Integration
To provide a holistic view, here's how your updated project structure and components might look after integrating the changes.
a. Wishlist.jsx Component
'use client';
import Image from "next/image";
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { CircleArrowLeft, X } from "lucide-react";
import ShoppingBag from "@/components/ShoppingBag";
import Loading from "@/components/Loading";
// Utility function to get the token
const getToken = () => {
return typeof window !== 'undefined' ? localStorage.getItem("token") : null;
};
// Utility function to get the cheapest price
const getCheapestPrice = (product) => {
const prices = [
product.price && product.price !== '0.00'
? parseFloat(product.price)
: Infinity,
...(product.sizes?.map((size) => parseFloat(size.price)) || []),
...(product.colors?.flatMap((color) => [
parseFloat(color.price),
...(color.sizes?.map((size) => parseFloat(size.price)) || []),
]) || []),
].filter((price) => !isNaN(price) && isFinite(price));
return prices.length > 0 ? Math.min(...prices) : null;
};
const WishlistItem = ({ id, name, price, imageUrl, onRemove }) => {
const router = useRouter();
const handleShoppingBagClick = () => {
router.push(`/products/${id}`);
};
return (
<div className="bg-white rounded-lg p-4 flex items-stretch space-x-4 mb-4">
<div className="relative w-[30%] min-h-[120px]">
<Image
src={imageUrl}
alt={name}
fill
unoptimized
className="object-cover rounded-md"
/>
</div>
<div className="flex-grow flex flex-col justify-center">
<h3 className="font-serif font-medium text-base text-center">{name}</h3>
<p className="text-sm text-center text-gray-600">
{price !== null ? `${price.toLocaleString()} IQD` : 'Price Unavailable'}
</p>
</div>
<div className="flex flex-col justify-center items-center space-y-2">
<button
onClick={() => onRemove(id)}
className="p-1"
aria-label={`Remove ${name} from wishlist`}
>
<X size={24} />
</button>
<button
onClick={handleShoppingBagClick}
className="bg-[#3B5345] rounded-full p-2"
aria-label={`View details for ${name}`}
>
<ShoppingBag width={24} height={24} />
</button>
</div>
</div>
);
};
export default function Wishlist() {
const router = useRouter();
const [wishlistItems, setWishlistItems] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
// Fetch Wishlist with Bearer Token
const fetchWishlist = async () => {
const token = getToken();
if (!token) {
setError('Authentication token not found. Please log in.');
setIsLoading(false);
return;
}
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_API}/wishlist`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Failed to fetch wishlist');
}
const data = await response.json();
setWishlistItems(data.wishlist.map(item => ({
id: item.id,
name: item.name,
price: getCheapestPrice(item),
imageUrl: `https://storage.naayiq.com/resources/${item.images[0]}`,
})));
} catch (error) {
console.error('Error fetching wishlist:', error);
setError(error.message || 'An unexpected error occurred');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchWishlist();
}, []);
const handleRemoveItem = async (id) => {
const token = getToken();
if (!token) {
setError('Authentication token not found. Please log in.');
return;
}
// Optimistically remove the item from the UI
const updatedItems = wishlistItems.filter(item => item.id !== id);
setWishlistItems(updatedItems);
try {
const response = await fetch(`${process.env.NEXT_PUBLIC_API}/wishlist/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Failed to delete item from wishlist');
}
// Optionally, you can show a success notification here
} catch (error) {
console.error('Error removing item from wishlist:', error);
setError(error.message || 'An unexpected error occurred while removing the item');
// Revert the optimistic update if the server request fails
fetchWishlist();
}
};
return (
<>
<header className="flex items-center mb-6">
<CircleArrowLeft size={52} strokeWidth={0.7} onClick={router.back} className="p-2 relative z-20 cursor-pointer" />
<h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">
Wishlist
</h1>
</header>
<main className="flex-grow flex flex-col items-center">
{isLoading ? (
<Loading />
) : error ? (
<div className="text-red-500 text-center">{error}</div>
) : wishlistItems.length === 0 ? (
<>
<div className="relative w-full h-[33vh]">
<Image
src="https://storage.naayiq.com/resources/empty_wishlist.gif"
alt="Empty wishlist"
fill
unoptimized
priority
quality={100}
className="object-contain"
/>
</div>
<section>
<p className="font-serif text-3xl text-center mb-2 font-semibold">Wishlist is empty!</p>
<p className="font-serif text-lg text-center leading-none">Tap the Heart Button to start</p>
<p className="font-serif text-lg text-center">saving your favorite items.</p>
<Link href="/" className="min-h-[56px] mt-4 items-center font-serif px-3 ssm:px-6 bg-[#3B5345] flex justify-center text-white text-xl rounded-lg">
Start Browsing
</Link>
</section>
</>
) : (
<div className="w-full max-w-md">
{wishlistItems.map(item => (
<WishlistItem
key={item.id}
id={item.id}
name={item.name}
price={item.price}
imageUrl={item.imageUrl}
onRemove={handleRemoveItem}
/>
))}
</div>
)}
</main>
</>
);
}
b. Key Points in the Updated Component
-
Token Management:
- Retrieves the token securely from
localStorage.
- Ensures that all API requests include the
Authorization header with the Bearer token.
-
Data Handling:
- Fetches comprehensive product details including
name, price, and images from the backend.
- Utilizes the
getCheapestPrice function to determine and display the lowest price.
-
UI Enhancements:
- Maintains the original design structure and styling.
- Adds error messages and loading indicators for better user feedback.
-
Accessibility:
- Adds
aria-labels to buttons for screen readers.
- Ensures that interactive elements are keyboard navigable.
-
Browser Compatibility:
- Ensures that all features used are compatible with modern browsers, including Safari.
- Recommends testing and polyfills where necessary.
4. Final Recommendations
-
Secure Token Storage:
- While
localStorage is used here for simplicity, consider more secure methods for storing tokens, such as HTTP-only cookies, to mitigate XSS attacks.
-
State Management:
- For larger applications, consider using state management libraries like Redux or Zustand to manage global state more efficiently.
-
Error Boundaries:
- Implement React Error Boundaries to catch and handle unexpected errors gracefully.
-
Performance Optimization:
- Use React's
memo and useMemo judiciously to prevent unnecessary re-renders.
- Consider code-splitting and lazy-loading components to improve initial load times.
-
Testing:
- Implement unit and integration tests to ensure that components behave as expected.
- Use tools like Jest and React Testing Library for effective testing strategies.
-
Continuous Browser Testing:
- Regularly test your application on different browsers and devices to catch and fix compatibility issues early.
By following these steps and recommendations, you should have a smoothly functioning Wishlist component that effectively uses Bearer tokens for authentication, displays product names and their cheapest prices, and maintains a stable and compatible design across browsers, including Safari.