【发布时间】:2021-08-27 09:20:05
【问题描述】:
我想将用户对象传递给我的 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>
)
}
【问题讨论】:
-
Next.js 中的自定义 _app 不支持 getServerSideProps 和 getStaticProps。尝试改用 getInitiapProps。
-
我遇到了类似的问题。 getInitialProps 将起作用,但会导致您的应用程序在服务器端呈现每个页面。 nextjs.org/docs/advanced-features/custom-app#caveats
标签: typescript next.js server-side-rendering aws-amplify react-props