0

In the following code, session is undefined when logging from the client after getting passed from getServerSideProps.

import { getServerSession } from 'next-auth/next';
import { authOptions } from './api/auth/[...nextauth]';
import StandardRecipeLogo from 'components/display/StandardRecipeLogo';
import { GetServerSideProps } from 'next';
import { Session } from 'next-auth';

const redirectUrl = 'http://localhost:3000/signin';

export default function Home({ session }: { session: Session }) {
  console.log(session);
  return (
    <div className="">
      <div className="flex items-center border-b mx-10 py-4">
        <StandardRecipeLogo styles={{ div: 'flex-1' }} />
      </div>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const session = await getServerSession(context.req, context.res, authOptions);
  if (!session) {
    return {
      redirect: {
        destination: redirectUrl,
        permanent: false,
      },
    };
  }
  console.log('session', session);
  return {
    props: {
      session: session,
    },
  };
};

However, changing the getServerSideProps return statement to extract the user object works fine, and the user is logged correctly on the client. What's going on here and why does passing the full session not work? The code that works:

  return {
    props: {
      user: session.user,
    },
  };
export default function Home({ user }: any) {
  console.log(user);
  return (
    <div className="">
      <div className="flex items-center border-b mx-10 py-4">
        <StandardRecipeLogo styles={{ div: 'flex-1' }} />
      </div>
    </div>
  );
}

The entire session object logs perfectly fine within getServerSideprops, but disappears after getting passed to the client.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
rolias4031
  • 233
  • 2
  • 10

1 Answers1

0

Props that you are passing from the server should be serializable. most likely some of the properties of session is undefined. so object is not serializable. to test if sessionserializable use this function from Reliable way to check if objects is serializable in JavaScript

function isSerializable(obj) {
  var isNestedSerializable;
  function isPlain(val) {
    return (typeof val === 'undefined' || typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number' || Array.isArray(val) || _.isPlainObject(val));
  }
  if (!isPlain(obj)) {
    return false;
  }
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (!isPlain(obj[property])) {
        return false;
      }
      if (typeof obj[property] == "object") {
        isNestedSerializable = isSerializable(obj[property]);
        if (!isNestedSerializable) {
          return false;
        }
      }
    }
  }
  return true;
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202