首页 > 解决方案 > Next.js 不会在 _app.tsx 中传递用户属性

问题描述

我想将用户对象传递给我的 next.js 应用程序中的所有页面。我没有将任何内容写入控制台或使用以下代码作为道具传递。放大部分似乎正在工作。

// _app.tsx

import type { AppProps } from "next/app"
import type { GetServerSideProps, GetServerSidePropsContext } from "next"
import Amplify, { Auth, withSSRContext } from "aws-amplify"
import { AmplifyAuthenticator, AmplifySignIn } from "@aws-amplify/ui-react"
import { config } from "../amplify.config"

Amplify.configure({ ...config, ssr: true })

MyApp.getServerSideProps = async (context: GetServerSidePropsContext) => {
    const appProps = await getServerSideProps(context)

    return { ...appProps }
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
    const auth = withSSRContext(ctx).Auth as typeof Auth

    let user: any
    try {
        user = await auth.currentAuthenticatedUser()
        console.log("user is authenticated:", user)
        return { props: { user: user } }
    } catch (err) {
        console.log("error: no authenticated user")
    }
}

export default function MyApp({ Component, pageProps }: AppProps) {
    return (
        <AmplifyAuthenticator>
            <AmplifySignIn hideSignUp usernameAlias="email" slot="sign-in" />
            <Component {...pageProps} />
        </AmplifyAuthenticator>
    )
}

标签: typescriptnext.jsserver-side-renderingaws-amplifyreact-props

解决方案


请阅读文档的这一部分next.js

https://nextjs.org/docs/advanced-features/custom-app

应用目前不支持 Next.js 数据获取方法,如 getStaticProps 或 getServerSideProps。

因此,您必须对自己进行一些更改_app.js才能实现这一目标。

您可以在这篇文章中找到解决方案: Next.js:减少数据获取并在页面之间共享数据


推荐阅读