'Next JS can not access to the localStorage

I building an application with next JS.

When authenticating the user via login page I can store the access token and refresh token to the local storage normally. But during authorization, when I am trying to get the access token from local storage I am getting an error called localstorage is not defined.

I guess because next JS is rendering the page on the server side, and there is not localstorage on the server.

So, how can I get around this? Any help would be appriciated.

// Set access token and refresh token to localstorage
const setTokens = (accessToken, refreshToken) => {
  localStorage.setItem("accessToken", accessToken);
  localStorage.setItem("refreshToken", refreshToken);
};

// Get access token from localstorage
const getAccessToken = () => {
  return localStorage.getItem("accessToken");
};

// Get refresh token from localstorage
const getRefreshToken = () => {
  return localStorage.getItem("refreshToken");
};

// Remove access token and refresh token from localstorage
const removeTokens = () => {
  localStorage.removeItem("accessToken");
  localStorage.removeItem("refreshToken");
};

export { setTokens, getAccessToken, getRefreshToken, removeTokens };

From above code only setToken() function is working.



Solution 1:[1]

use your function in useEffect

const [accessToken, setAccessToken] = useState(null)
const [refreshToken, setRefreshToken] = useState(null)
useEffect(() => {
  try {
    const accToken = getAccessToken();
    const refToken = getRefreshToken();
    setAccessToken(accToken)
    setRefreshToken(refToken)
  } catch (e) {
  }
}, [])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iamhuynq