Home > OS >  localStorage is not defined in Nextjs, Redux and Typescript
localStorage is not defined in Nextjs, Redux and Typescript

Time:09-06

I'm facing a problem with my project. The problem is ReferenceError: localStorage is not defined. I'm using Nextjs, and Redux with Typescript.

Screenshot_2

const storedUser: string | null = localStorage.getItem('user');
const user: DisplayUser | null = !!storedUser ? JSON.parse(storedUser) : null;

const storedJwt: string | null = localStorage.getItem('jwt');
const jwt: Jwt = !!storedJwt ? JSON.parse(storedJwt) : null;

I'm using these 2 variables user and jwt in here initialState

const initialState: AuthState = {
    user: user,
    jwt: jwt,
    isLoading: false,
    isSuccess: false,
    isError: false,
}

And initialState are used in authSlice function

export const authSlice = createSlice({
  name: 'auth',
    initialState,
    reducers: {
        reset: (state) => {
            state.isLoading = false;
            state.isSuccess = false;
            state.isError = false;
        }
    },
})

CodePudding user response:

If you use React.js or Next.js and you need to check if you're on the browser (can use localStorage) or on the server (can't use localStorage), check that the window variable is not undefined :

if (typeof window !== 'undefined') {
  console.log('You are on the browser')
  //            
  • Related