Home > other >  Next.js TypeError: Cannot read property '' of undefined when trying to console log api res
Next.js TypeError: Cannot read property '' of undefined when trying to console log api res

Time:11-27

So this is kind of a weird error. What I'm trying to do in my Next.js app is to console log contents of an API call to see what I get. This API function just checks if a user is logged in and if so then I'll render a certain section of code. From my auth.js actions file which get a cookie that contains user info of a signed in user from local storage:

export const isAuth = () => {
if (process.browser) {
    const cookieChecked = getCookie('token');
    if (cookieChecked) {
        if (localStorage.getItem('user')) {
            return JSON.parse(localStorage.getItem('user'));
        } else {
            return false;
        }
    }
}

};

In my pages folder I have a file [username].js where right now I'm just trying to log a certain piece of information about the user in this instance the username:

{ isAuth().username ? console.log(isAuth().username)  : "" }

I'm even checking to make sure it's set however even then I get a TypeError: Cannot read property 'username' of undefined

However if I just log the entire user object { isAuth() ? console.log(isAuth()) : "" } it console logs just fine. Here's what is returned:

{
"_id": "5f7a39ab7acc30a29c5280df",
"username": "dylancougar",
"name": "Dylan Cougar",
"role": 2}

So all the info is there however when I try to isolate any info in the object I get the error. Even more strange is every once in a while if the offending bit code is commented out, and I uncomment it and save it will actually work sometimes, however, if I reload the page error returns. I'm not an expert on Next.js, so perhaps there is something obvious that I'm overlooking.

CodePudding user response:

The problem here is that next.js renders your data in the server first and process.browser is undefined in the server. So do the following:

  export const isAuth = () => {
  let user = false
  if (process.browser) {
    const cookieChecked = getCookie('token');
    if (cookieChecked) {
      if (localStorage.getItem('user')) {
        user = JSON.parse(localStorage.getItem('user'));
        return user;
      } 
    } 
  }
  return user;

This should work.

  • Related