最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Auth0 User object in getServerSideProps? - Stack Overflow

programmeradmin2浏览0评论

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:

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:

Share Improve this question edited Oct 4, 2021 at 1:13 Sriharsha K asked Oct 3, 2021 at 8:27 Sriharsha KSriharsha K 3232 gold badges6 silver badges19 bronze badges 5
  • You're importing withApiAuthRequired but using withPageAuthRequired in the code, is that a typo? Could you show all the imports you're using from @auth0/nextjs-auth0? – juliomalves Commented Oct 3, 2021 at 12:23
  • @juliomalves sorry typing mistake, I have updated the imports. – Sriharsha K Commented Oct 4, 2021 at 1:13
  • Are you intentionally calling withPageAuthRequired twice by wrapping both getServerSideProps and function Profile? Don't you just need a single wrap function call? – Dejan Vasic Commented Oct 19, 2021 at 10:41
  • @DejanVasic since I am using auth0 google login I wanted save those credentials in my database. Therefore, wanted to access the user object in serversideprops. – Sriharsha K Commented Oct 20, 2021 at 1:11
  • @SriharshaK Using Google or whatever authentication mechanism in this should work without an additional call to withPageAuthRequired. I'll post some sample code that worked for me. BTW, I'm also using google auth as well as option for username/password. – Dejan Vasic Commented Oct 20, 2021 at 2:39
Add a ment  | 

2 Answers 2

Reset to default 5

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

You only need to wrap the getServerSideProps. Here's an example that worked for me:

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

import db from '.';

interface Props {
  user: DbUser;   // Not the auth0 user
}

export default function Profile({ dbUser }: Props) {
  return <div>{JSON.stringify(dbUser, null, 2)}</div>;
};


export const getServerSideProps = withPageAuthRequired({
  getServerSideProps: async ({ req, res }) => {
    const auth0User = getSession(req, res);

    // Fetch the user from the db (by email)
    let user = await db.user.findUnique({ where: { email: auth0User?.user.email } });

    // You might want to move the creation of the user somewhere else like afterCallback
    // Checkout https://auth0.github.io/nextjs-auth0/modules/handlers_callback.html
    if (!user) {
      user = db.user.create(auth0User?.user);
    } 

    return {
      props: {
        dbUser: user,
      },
    };
  },
});

发布评论

评论列表(0)

  1. 暂无评论