Ways to tackle the issue of localStorage undefined error

My current struggle involves using next js. Whenever I attempt to utilize localStorage on my page, an error pops up stating that localStorage is not defined. After scouring through numerous articles, the common advice is to switch to window.localStorage, but unfortunately, this also triggers an error mentioning window is not defined. This issue has left me feeling incredibly frustrated. The specific area where I am trying to implement localStorage is within the serverSideProps function:

export async function getServerSideProps(context) 
    let user = {
        user:"",
        isAuth:""
    };
    const response = await fetch(
        `${server}/api/user/getUserData`, {
        method: "POST",
        headers: {
            "mode": "cors",
            'Content-Type': 'application/json',
            'auth-token': localStorage.getItem('token')
        },
        body: JSON.stringify({ username })
    });
    const result = await response.json()
        .then(user => {

            if (user["user"][0] != null) {
                user.user = user["user"][0]
                user.isAuth = user.isAuth;
            }
            else {
                user.isAuth = 'false';
            }
        })
        .catch(err => console.log(err))

    return {
      props: { user
    }, // will be passed to the page component as props
    }
  }

I am at a loss for finding a solution to this particular type of problem. Can anyone offer guidance or suggestions?

Answer №1

When using Next.js, the function getServerSideProps runs exclusively on the server side and not in your browser. This is why objects like window or localstorage will be undefined. It's important to note that you cannot access localstorage on the server side as it is a browser specific method.

If you want to learn more about this topic, check out the discussion here: https://github.com/vercel/next.js/discussions/16824

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

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Attempting to implement ajax for form submission, however finding that the $_POST array is coming back as empty

I'm attempting to send JavaScript arrays to a new page using Ajax. Although there are numerous questions on this topic on Stack Overflow, I have decided to implement Ajax in the following manner after examining various answers: var test = {}; test[& ...

Experiencing difficulties while attempting to organize an array?

// const first = data.groups_with_selected[7]; // const second = data.groups_with_selected[20]; // data.groups_with_selected.splice(2, 0, first, second); // data.groups_with_selected.splice(9, 1) // data.groups_with_selected ...

Is there a way to use JQuery to determine which button in a table was clicked and retrieve all the data from that specific row?

Below is the HTML code: <table class="table table-stripped table-bordered table-hover centerAll" cellpadding="10"> <thead> <th>Nombre</th> <th>Descripci ...

Tips for navigating the HTML DOM without using window.scrollBy(x, y) (specifically for scrolling within an element)

Desiring to scroll down along with my selected document, I experimented with the following code. window.scrollTo(x, y); const body = document.getElementsByClassName("body")[0]; body.scrollTo(x, y); However, there are instances where it returns "undefined ...

Develop a real-time preview of the form inputs

While working on a multistep form, I am exploring the idea of creating a live preview that shows values entered into different input fields, text areas, and radio buttons. Currently, I have successfully built the form and made some progress using the foll ...

Issue with animated cursor function not activating when used with anchor links

I've spent hours searching for a solution but I can't seem to find one. I'm attempting to modify the codepen found at https://codepen.io/Nharox/pen/akgEQm to incorporate images and links, however, two issues are arising. The first issue is t ...

Error in Angular: Http Provider Not Found

NPM Version: 8.1.4 Encountered Issue: Error: Uncaught (in promise): Error: Error in ./SignupComponent class SignupComponent_Host - inline template:0:0 caused by: No provider for Http! Error: No provider for Http! The error message usually indicates the a ...

The unfortunate timing of the multi-material design lite snackbar

I am currently working on customizing notifications that appear when a Symfony entity is successfully updated. What I have implemented so far can be found here : var messagesTypes = { "notice": ["This is a green NOTICE"], "error": ["This is a red E ...

React Hook Form - The onSubmit function is unresponsive

I'm currently working on a small project using NextJS 14 and implementing react-hook-form for easier form submission and input handling. Unfortunately, I've been struggling with an issue for the past few days despite trying various troubleshootin ...

Every item in the list must be assigned a distinct "key" property

I am receiving a warning message that states: Warning: Each child in a list must have a unique "key" prop. Refer to https://reactjs.org/link/warning-keys for more information. at Head (webpack-internal:///./node_modules/next/dist/pages/_document.js:304 ...

Looking for a dropdownlist with checkboxes in asp.net mvc but without the use of Entity Framework

I am in need of a dropdown list with checkboxes in asp.net mvc. The issue is that my view already has a layout page with existing script files, which seem to be causing a disturbance in the original layout. I have tried various solutions such as rearrangi ...

What is the best way to switch between two components using vue.js?

I have a scenario where I need to toggle between two components, Register.vue [`my_reg-page`] and Login.vue [`my-signin_page`]. If the user opens the register page in the browser (using the /register URL), clicking on the Login heading will toggle the user ...

Creating a Unique CSS Grid Border with Custom Images

I have a client project using nextjs and the design calls for a component with a custom border on a responsive CSS grid. I've successfully created the CSS grid with all the necessary content, but I'm struggling to add the required border as per t ...

"Utilizing MongoDB's findAndModify() allows for the integration of a query within the

Currently, I am working on a Node application that involves CRUD operations. One particular challenge I am facing is with the save() method in one of my data objects. This method needs to update an existing record if the object has an id present in the col ...

Decoding entities in a jQuery AJAX form

I am working on a jQuery AJAX form to add, edit, and delete usernames in a MySQL database. When I retrieve data with special characters from the database, I want to populate the modal edit form with entity-decoded characters. This means that characters lik ...

Issues with jQuery jGrowl functionality

I've been struggling to get the jGrowl feature working on my website. Despite setting up the CSS and JS correctly as shown below: <script type="text/javascript" src="<?php echo $base; ?>jgrowl/jgrowl.js"></script> <link type="tex ...

Is there inconsistency in the behavior of json.parse when given the same input?

This query pertains to the differentiation in outputs resulting from various inputs I am not seeking guidance on achieving a specific output. The reason behind the discrepancy in output between two scenarios, despite using the same argument for the JS ...

Implementing advanced checkbox filtering feature in React

Does anyone have experience with creating dynamic Checkbox filtering in React using Material-UI? I'm finding it challenging because the checkbox options are generated dynamically from incoming data and need to be categorized by type of Select componen ...

The distinction between plural and singular array identifiers in JavaScript

The functionality of this code in Chrome 59.0.3071.115 is causing confusion for me: var names = ["Cat 1", "Cat 2"]; console.log(names); When executed, it displays an array object; however, var name = ["Cat 1", "Cat 2"]; console.log(name); Instead print ...