2

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.

1
  • There might be a point when your page initially loads where isAuth() is returning undefined because of process.browser evaluating to false. When this happens you'll get your error. Try doing something like { isAuth() && isAuth().username ? console.log(isAuth().username) : "" } to make sure its not undefined before accessing the property. Commented Nov 27, 2021 at 3:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.