I'm using Next.js 14 for my project. One of the features of the site is to add products to favorites, where the product IDs are stored in localStorage.
In the Page.jsx file (located at /favorites), I have the following code:
import { getFavoriteProperties } from '@/database/getProperties'
export default async function Favorites() {
let favoriteProperties = [];
if (typeof window !== "undefined") {
favoriteProperties = JSON.parse(localStorage.getItem('FAVORITE_PROPERTIES')) || [];
console.log(favoriteProperties);
}
const properties = await getFavoriteProperties(favoriteProperties);
console.log(properties);
return (
<div>
<h1>Favorites</h1>
</div>
)
}
As you can see, the problem with the code is that I need to retrieve the values stored in localStorage, but this won't work since Page.jsx is executed server-side (SSr).
The obvious solution would be to add a 'use client' directive at the top of the file, but the problem with that is the function **getFavoriteProperties **(which receives the IDs from localStorage) is used to get information from the database using Sequelize, and it needs to be executed server-side.
I have tried many solutions from forums and all over the internet, even those that I knew probably wouldn't work. Most of my attempts have been focused on decoupling the client-side logic to retrieve the IDs from localStorage and then sending them to the getFavoriteProperties function.