Next.js does not recognize the term 'localstorage'

I am currently in the process of transitioning an application from React to Next

Interestingly, in React, I encounter no errors with this particular code snippet:

let [authTokens, setAuthTokens] = useState(() => localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null)

let [user, setUser] = useState(()=> localStorage.getItem('authTokens') ? jwt_decode(localStorage.getItem('authTokens')) : null)

However, upon attempting to use it in Next.js, an error arises.

https://i.stack.imgur.com/Yj20d.png

The issue appears to be due to the fact that Next.js initially renders on the server side where local storage is unavailable.

This function is responsible for setting the data in local storage.

let loginUser = async (e) => {
        e.preventDefault();
        let response = await fetch('http://127.0.0.1:8000/api/token/', {
            method:'POST',
            headers:{
                'Content-Type': 'application/json'
            },
            body:JSON.stringify({'email':e.target.username.value, 'password':e.target.password.value})
        })
        let data = await response.json()
        console.log(data)
        console.log(data.access)
        if(response.status == 200) {
            setAuthTokens(data)
            setUser(jwt_decode(data.access))
            localStorage.setItem('authTokens', JSON.stringify(data))
            router.push('/')
        } else {
            alert('something went wrong')
        }
    }

Answer №1

When your webpage is loaded on the server side, it does not have access to any browser specific APIs. To work with the localStorage, you should ensure that it is only accessed when the application is running in a browser environment. One way to achieve this is by waiting for the component to be mounted before accessing the localStorage.

function MyComponent(){
  // This code block will run only in a browser environment
  useEffect(()=>{
  // Accessing local storage here
  },[])
}

Answer №2

After some troubleshooting, I was able to resolve the issue by transferring the logic from the useState function to a useEffect hook.

The original code looked like this:

let [authTokens, setAuthTokens] = useState(() => localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null)

let [user, setUser] = useState(()=> localStorage.getItem('authTokens') ? jwt_decode(localStorage.getItem('authTokens')) : null)

I made adjustments and moved the logic into the useEffect hook:

let [authTokens, setAuthTokens] = useState(null)
let [user, setUser] = useState(null)

    useEffect(() => {
        
            if(localStorage.getItem('authTokens')) {
                setAuthTokens(JSON.parse(localStorage.getItem('authTokens')))
                setUser(jwt_decode(localStorage.getItem('authTokens')))
            } else {
                setAuthTokens(null)
                setUser(null)
            }
        

Answer №3

Feel free to implement the following code snippet:

if (typeof window !== "undefined") {
   if(response.status == 200) {
            setAuthTokens(data)
            setUser(jwt_decode(data.access))
            localStorage.setItem('authTokens', JSON.stringify(data))
            router.push('/')
        } else {
            alert('there was an issue, please try again')
        }
  }

Answer №4

To initialize it, assign a placeholder value in the useState hook and then update it with useEffect once the application loads.

Keep in mind that your setAuthTokens function will continue to function as expected within the loginUser function without needing any modifications.

Answer №5

When using the useState hook, it is important to first check if the window object is defined before accessing the local storage. Here is an example of how you can do this:

let [authTokens, setAuthTokens] = useState(
  () => typeof window !== "undefined" 
    ? localStorage.getItem('authTokens') 
        ? JSON.parse(localStorage.getItem('authTokens')) 
        : null)

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

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Retrieve the nested value of an object using the specified key field

When using the DataGrid component from material-ui to display my data in a table, I encountered an issue with accessing nested values. Specifically, I have a nested array of data but am unable to retrieve the nested value within the datagrid using the key ...

Formik invoked `handleChange`, however, you omitted to provide an `id` or `name` attribute for your input field: undefined

I'm currently exploring the integration of Formik with a MaterialUI Select component. You can find my sandbox project here: https://codesandbox.io/s/lively-wind-75iliv?file=/src/App.tsx After selecting a new value from the dropdown list, I've n ...

Creating unique appbars for different sections on my sidebar in ReactJs

I am trying to implement a responsive drawer and AppBar using material-ui (@material-ui/core). My goal is to display a specific AppBar for each section of the drawer. For instance, when the user navigates to the Timetable section, I want the AppBar label t ...

Order of Actions not being Dispatched by Redux Thunk

Using redux thunk presents a challenge for me. When I dispatch uploadClientImage, it creates an image object in the database and returns the image id. I require both image ids before creating client_info. The issue arises when the axios post to clients i ...

"When attempting to access a model that has been added in the Prisma schema, the error message 'Property does not exist' is

Currently, I am working on a ReactJS project using the NextJS Framework and Prisma for managing connections and database queries. Within my local project, everything runs smoothly with the Support model. However, when I deploy the project to my production ...

Issue with converting response to JSON format

I've encountered an issue while attempting to extract information from a React form and submit it to my Rails database. The error message "unexpected token '<' at position 0" suggests that the response is still in HTML format instead of J ...

"Uh-oh! Encountered a new unexpected runtime error. Can't seem

While working on my portfolio in Next.js, I encountered an issue. I added a header to display on all pages by placing it in _app.js without making any changes to _document.js. Here is the error message: Unhandled Runtime Error Error: No router instance fo ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

Ensure redirect is delayed until async data is fetched

Having come from the Angular world, I found it really easy and convenient to resolve data for routes. However, now that I'm using React, I'm unsure about how to achieve the same functionality. I would like to add an async data loader for my rout ...

Can you explain the concept of a "nullified object" within the SyntheticEvent of React?

After some research, I discovered that React handles DOM event handlers using SyntheticEvent objects. These objects are pooled for performance reasons, but they cannot be used in asynchronous contexts like setTimeout() or setState(). Despite this limitat ...

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

Using React Native to create a concise text component that fits perfectly within a flexbox with a

Within a row, there are two views with flex: 1 containing text. <View style={{ flexDirection: "row", padding: 5 }}> <View style={{ flex: 1 }}> <Text>Just a reallyyyyyyyy longgggg text</Text> </View> ...

Error encountered when mapping through images in Next.js with TypeScript due to a missing mandatory 'src' property

Issue: I am encountering an issue where the string entries from an array of objects are displayed correctly, but the images in the Image Component do not load dynamically in the src. The images are imported in the constants.js file and exported via the &a ...

Children in a WPGraphQL query for menus in Next.js are returning as null

When utilizing WPGraphiQL IDE, the data displays correctly as shown below: https://i.stack.imgur.com/wBwl8.png However, when I attempt the same query using Apollo Client on the Front-End, the children of the menu are returned as null. Retrieving data th ...

Issue arising from background change upon component focus

My component needs to change its background color when focused, but for some reason it's not working. The hover effect works fine, but the focus doesn't. Can anyone assist me with this issue? import { CardContainer } from './styles' in ...

Authenticating NextJS static sites using SSG (Static Site

Scenario My project involves creating a platform where users can pay to access blog content from various bloggers. Chosen Solution I decided to use NextJS for building static content (SSG). With the fallback option, I am able to generate static content e ...

React component unable to trigger signalR connection.hub function

Setting up a chatboard using signalR to notify users of new comments on posts. Using React and encountering issues with event listeners in different components. The hub code: public class CommentHub : Hub { public void UpdateComments(int postId) ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...