Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Auth0 User object in getServerSideProps?

I am trying to use Auth0 with NextJS for user authentication. After login I want to access the user object in getServerSideProps. I followed this link below,

Stackoverflow however, when I try to paste the code typescript error is shown. I have attached code and error below. Please let me know how can this be resolved.

import { withPageAuthRequired } from '@auth0/nextjs-auth0';

  export default withPageAuthRequired(function Profile({ user, newData }) {
    return (
      <>
        <div>{user.name}</div>
      </>
     )
   });

  export const getServerSideProps = withPageAuthRequired({ 

    async getServerSideProps (context){
      return {
         props: {
           newData: "user"
         }
       }
     }
   });

error code:

{
   "resource": "/Users/username/Downloads/proj/projectname/pages/profile.tsx",
   "owner": "typescript",
   "code": "2345",
   "severity": 8,
   "message": "Argument of type '{ getServerSideProps(context: any): Promise<{ props: { newData: string; }; }>; }' is not assignable to parameter of type 'ComponentType<WithPageAuthRequiredProps>'.\n  Object literal may only specify known properties, and 'getServerSideProps' does not exist in type 'ComponentType<WithPageAuthRequiredProps>'.",
   "source": "ts",
   "startLineNumber": 73,
   "startColumn": 11,
   "endLineNumber": 73,
   "endColumn": 29
}

Screenshot: enter image description here

like image 524
Sriharsha K Avatar asked Nov 02 '25 05:11

Sriharsha K


1 Answers

You have example here.

Based on you example:

import { getSession, withPageAuthRequired } from '@auth0/nextjs-auth0';

export default function ProtectedPage({user}) {
  return (
    <>
      <div>{user.name}</div>
    </>
  )
});

export const getServerSideProps = withPageAuthRequired({
  //returnTo: '/foo',
  async getServerSideProps(ctx) {
    const session = getSession(ctx.req, ctx.res);
    //check the console of backend, you will get tokens here
    console.log(session);
    return {props: {
      customProp: 'bar'
    }};
  }
});

Please notice the difference between getSession and {user}: you can define some actions as a "redirect to" in getServerSideProps. What does it mean? It means you can, for example, redirect users with no access to a custom page, for example, 404

P.S. you don't have context, you need to have ctx variable

like image 183
illia chill Avatar answered Nov 03 '25 20:11

illia chill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!