[英]How to get Auth0 User object in getServerSideProps?
我正在嘗試使用 Auth0 和 NextJS 進行用戶身份驗證。 登錄后,我想訪問 getServerSideProps 中的用戶對象。 我按照下面的鏈接,
但是,當我嘗試粘貼代碼打字稿時,會顯示Stackoverflow錯誤。 我在下面附上了代碼和錯誤。 請讓我知道如何解決這個問題。
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"
}
}
}
});
錯誤代碼:
{
"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
}
您只需要包裝getServerSideProps
。 這是一個對我有用的例子:
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,
},
};
},
});
基於你的例子:
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
function Example({newData}) {
return (
<>
<div>{user.name}</div>
</>
)
});
export const getServerSideProps = withPageAuthRequired({
async getServerSideProps (ctx){
const session = getSession(ctx.req, ctx.res);
//check the console of backend
console.log(session)
return {
props: {
newData: "user"
}
}
}
});
export default Example;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.