Error: The "use client" component does not recognize either window or localStorage

I'm currently working on creating a wrapper function that can be used in every dashboard component.

"use client";

const UserWrapper = ({ children }) => {
  const user = JSON.parse(window.localStorage.getItem("ysg_u"));

  return (
    <div>
      {user?.token ? (
        children
      ) : (
        <div className="min-h-screen flex flex-col justify-center items-center">
          <TbFaceIdError className=" w-8 h-8 mb-2" />
          <p className="font-headliner text-3xl tracking-wider">ACCESS DENIED</p>
          <p className="text-xl -mt-2 font-teko">
            Please{" "}
            <Link href={"/login"} className="text-orange-700 underline">
              Login
            </Link>{" "}
            First
          </p>
        </div>
      )}
    </div>
  );
};

export default UserWrapper;

Removed all the imports for long code. The error is showing but the function works. However, I am having trouble completing the build command in Vercel:

 event compiled client and server successfully in 729 ms (2087 modules)
- error src/components/Wrapper/user.wrapper.js (11:26) @ window
- error ReferenceError: window is not defined
    at UserWrapper (./src/components/Wrapper/user.wrapper.js:22:29)
   9 | 
  10 | const UserWrapper = ({ children }) => {
> 11 |   const user = JSON.parse(window.localStorage.getItem("ysg_u"));
     |                          ^
  12 | 
  13 |   //   useEffect(() => {
  14 |   //     if (!user?.admin) {
- warn The server is running out of memory, restarting to free up memory.
- wait compiling...
- event compiled client and server successfully in 468 ms (2087 modules)

Although I'm using the use client tag, I'm puzzled as to why it keeps indicating that either window or localStorage is undefined.

If I utilize the useEffect and useState hooks solution, it will work. The issue lies in the fact that with every route change, the screen momentarily displays no user data before loading the page because useState takes a few milliseconds to load the localStorage into state initially.

Does anyone have a proper solution to this problem? I'm using Next.js 13.

Thank you ❤️

Answer №1

When using Next.js, it's important to remember that even client components first render on the server. Therefore, anything browser-specific like localStorage should not be called in a client component body directly; instead, it should be used inside useEffect or event handlers.

To address the page flicker issue you mentioned, consider implementing the following solution:

"use client";

import { useEffect, useState } from "react";

const UserWrapper = ({ children }) => {
  const [user, setUser] = useState();

  useEffect(() => {
    setUser(() => {
      try {
        return JSON.parse(window.localStorage.getItem("ysg_u"));
      } catch (error) {
        return null;
      }
    });
  }, []);

  // Optionally show a loading state:
  if (user === undefined) {
    return null;
  }

  return (
    <div>
      {user?.token ? (
        children
      ) : (
       ...
      )}
    </div>
  );
};

export default UserWrapper;

Avoid trying the window !== "undefined" hack as it may lead to hydration errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieve dynamic styling and adjust window size using window.open

My mind is exhausted after days of trying: function prtDiv( o ) { var css = 'body {font:normal 10px Arial;}' ; var wo = window.open('','print','width=600,height=600,resizable=yes'); wo.document.write( '<he ...

Steps for executing the npm 'filestream' sample code

After conducting some research, I came across the filestream module which allows for the usage of a file stream API in the browser. https://github.com/DamonOehlman/filestream The author has provided an example usage code named drag-n-drop.js. Here is a s ...

What is the recommended method for writing JavaScript scripts with AJAX in a Rails application? How can URLs be incorporated into the script effectively?

When incorporating AJAX into my Rails application, I encounter difficulties when specifying the URL for the request within a script. While it is recommended to use helpers like my_resource_path instead of manually writing paths, these helpers do not functi ...

Leveraging asynchronous data in a synchronous manner

I am dealing with tax rate data stored in the database to ensure easy updates when necessary. However, JavaScript's asynchronous nature complicates accessing this data as it requires promises or callbacks to retrieve query results. Is there a solution ...

The Java Servlet change did not trigger an update in the web content

While using Eclipse to develop a website where Servlet sends data to JSP, I encountered an issue. Despite modifying the data in the Servlet, it continued to send outdated information to the JSP page. I attempted the following options: Menu - Project - cle ...

Implementing Mongoose's save() function within Formidable's parse() function in a NextJS API endpoint

Currently, I am utilizing both the formidable package and mongoose in my NextJS application. I have successfully implemented an API call that allows users to upload a photo along with some additional data. The file processing aspect using formidable is fun ...

What are the steps to execute Mike Bostock's D3 demonstrations?

I've been attempting to run Mike Bostock's See-Through Globe demonstration, but I encountered issues with the correct referencing of his json files when attempting to replicate it locally. The problem stems from this particular line of code: d3. ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

How can I effectively refresh the provider_token / access token for Discord in NextJS with Supabase Auth?

Currently, I have encountered an issue with my NextJs project using Supabase Auth for authentication. I am currently utilizing the Discord provider and everything works fine initially. However, after a few minutes, the session object gets updated and the p ...

extract elements from dataset

Attempting to splice an array but encountering index issues var kode_pelayanan = []; function deleteKodePelayanan(index){ kode_pelayanan.splice(index, 1); console.log(kode_pelayanan); } Experimented in the console with an array for kode_pelayanan ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

Is it necessary to have the script tag as the first tag in the body of the HTML?

I have a script file that needs to be included by third party implementors on their web pages. It is crucial for this script to be the first tag within the body element, like so: <body> <script type="text/javascript" src="/my_script.js"></ ...

Is it feasible to programmatically click a div button in C# using WebBrowser?

Exploring the capabilities of WebBrowser in C#, I came across a website that features a button without an ID, but rather nested within a div element. <div class="pc-image-info-box-button-btn-text pc-cursor"><i class="fa fa-heart" aria-hidden="tru ...

How can I position text in the top right corner of a v-card's v-img component in Vuetify.js?

I am using Vuetify.js and I am trying to show a single word on the right side of an image within a v-card: <v-card> <v-img src="https://cdn.vuetifyjs.com/images/cards/desert.jpg" aspect-ratio="2.75"> <span class= ...

Is there a way to bypass the initial result when using document.querySelectorAll?

this is my own unique html content <div class="content-body"> <table style="text-align:center;" class="table table-bordered"> <tbody> <tr> <th>Text Line</th> </tr> <tr> <td> ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

JavaScript - incorrect order for compiling

Is the user already in my SQLite database? If the user exists: return 500 (ERROR!!) If the user does not exist: return 200 (OK) This is my Node.js + Express script running on the server side. app.post('/adduser', function(req, res){ db.se ...

How can I implement a GET request in NextJS 13.4 to fetch all items or by a specific ID? Should I use Response, NextAPIResponse, or NextResponse with the latest App Router features?

What is the proper method for performing a GET request (either to retrieve all items or by a specific ID) in NextJS 13.4 using the new App Router? The old approach of handling GET requests with NextAPIRequest, NextAPIResponse, checking if (req.method === ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...