i make system jsonwebtoken in reactjs and use nextjs. i find problem when i run the code in browser that is localStorage is not defined.
this is my code in file AuthStudentContext.js
import React from 'react'
import axios from 'axios'
const axiosReq = axios.create()
const AuthStudentContext = React.createContext()
export class AuthStudentContextProvider extends React.Component {
constructor() {
super()
this.state = {
students: [],
student: localStorage.getItem('student') || {},
token: localStorage.getItem('token') || "",
isLoggedIn: (localStorage.getItem('student' == null)) ? false : true
}
}
login = (credentials) => {
return axiosReq.post("http://localhost:4000/api/login", credentials)
.then(response => {
const { token } = response.data
localStorage.setItem("token", token)
this.setState({
token,
isLoggedIn: true
})
return console.log(response)
})
}
and show error localStorage is not defined
To solve the "ReferenceError: localStorage is not defined" error, make sure to only use the localStorage object in the browser. The localStorage property is defined on the window object and is not available on the server - e.g. in Node. js or when using server side rendering with Next. js.
This is because localStorage is not defined on the window object, and Next. js performs a server render before the client render. Therefore, you'll not be able to access localStorage until the page has loaded on the client and the window object has been defined.
As you mentioned localStorage and sessionStorage are not available on the server. You could use cookie and access them inside getServerSideProps via req. cookies .
I never touched nextjs but i guess its equivalent to Nuxt.js. So it does server side rendering while you try to access localstorage on the client side.
You will need to use componentDidMount()
for this. Here an example
componentDidMount(){
localStorage.setItem('myCat', 'Tom');
alert("Tom is in the localStorage");
}
EDIT:
Otherwise you could try with process.browser
if (process.browser) {
localStorage.setItem("token", token);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With