I'm currently working on my first member area with next.js. For now I want to store some data in localStorage (token, expiresAr, userInfo) - btw, later this is going to be stored in http-only cookie.
With the following code I get the error: "LocalStorage is not defined":
const AuthProvider = ({ children }) => {
const token = localStorage.getItem("token");
const userInfo = localStorage.getItem("userInfo");
const expiresAt = localStorage.getItem("expiresAt");
const [authState, setAuthState] = useState({
token,
expiresAt,
userInfo: userInfo ? JSON.parse(userInfo) : {},
});
const setAuthInfo = ({ token, userInfo, expiresAt }) => {
localStorage.setItem("token", token);
localStorage.setItem("userInfo", JSON.stringify(userInfo));
localStorage.setItem("expiresAt", expiresAt);
setAuthState({
token,
userInfo,
expiresAt,
});
};
I already tried to use the following snipped:
if (typeof window !== 'undefined') {
const token = localStorage.getItem("token");
const userInfo = localStorage.getItem("userInfo");
const expiresAt = localStorage.getItem("expiresAt");}
But with this code I get the error "token is undefined". So I tried to define the variables const token, const userInfo and const expiresAt globally. But then I get the error: "Unexpected token o in JSON at position 1".
I'm a little stuck with this problem, so any help is appreciated! Thanks!