Why aws-cognito-next getServerSideAuth returns null?

Viewed 210

I'm using the npm module aws-cognito-next to implement authentication for one of my app. There the function getServerSideAuth(context.req); seems to not working as expected:

export async function getServerSideProps(context) {
    // getServerSideAuth will parse the cookie
    const initialAuth = getServerSideAuth(context.req);
    return { props: { initialAuth } };
}

Then in the same page which is Home (/pages/home.js) I use this returned initialAuth as follows:

const Register = ( {initialAuth} ) => {
    console.log("initialAuth is: " + util.inspect(initialAuth))
    const auth = useAuth(initialAuth);
    ...
    //other logic
    ...
}

But I get out put as: initialAuth is: null. So why doesn't initialAuth isn't getting returned from serverside? What am I doing wrong here?

1 Answers

getServerSideAuth checks to see if user is logged in and returns tokens that can be used in useAuth. You can check for null and add logic to send the user to the login/logout pages.

const Register = ( {initialAuth} ) => {
  const auth = useAuth(initialAuth);
  const { login, logout } = useAuthFunctions();

  return (
    <React.Fragment>
      {auth ? (
        <button type="button" onClick={() => logout()}>
          sign out
        </button>
      ) : (
        <React.Fragment>
          <button type="button" onClick={() => login()}>
            sign in
          </button>
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

For more information on useAUth see here.

Related