0

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.

1 Answer 1

0

Instead localStorage.getItem('FAVORITE_PROPERTIES'), use this globalThis.localStorage.getItem('FAVORITE_PROPERTIES') to get the localstorage value.

Otherwise, you can use a state manager like redux or Zustand.

2
  • Thank you for the quick response, Dileepa Mabulage. I tried with globalThis.localStorage.getItem('FAVORITE_PROPERTIES') but the error is the same since Page.jsx won't have access to the client's localStorage. I will look into the possibility of using Redux or Zustand, but I refuse to believe that there isn't something easier for something so simple. Without a doubt, this is a major drawback of Next JS from what I've encountered. Commented May 16 at 2:15
  • I guess local storage won't support server components; I want to share a state on the client side; Zustand will be a great choice. Commented May 17 at 3:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.