You need to enable JavaScript to run this app. Next.js中_app.tsx无法传递user属性到所有页面问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中_app.tsx无法传递user属性到所有页面问题排查

问题根因

Next.js 仅支持 pages 目录下的页面级组件定义getServerSideProps生命周期,自定义_app.tsx中导出的getServerSideProps不会被框架执行,这是你看不到控制台输出、也无法拿到user属性的核心原因。

解决方案

方案1:使用_app.tsx支持的getInitialProps获取用户(适合全站SSR的场景)

修改后的_app.tsx代码如下:

// _app.tsx
import type { AppProps } from "next/app"
import App from "next/app"
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 })

export default function MyApp({ Component, pageProps, user }: AppProps & {user: any}) {
    return (
        <AmplifyAuthenticator>
            <AmplifySignIn hideSignUp usernameAlias="email" slot="sign-in" />
            {/* 把user合并到pageProps传递给所有页面 */}
            <Component {...pageProps} user={user} />
        </AmplifyAuthenticator>
    )
}

MyApp.getInitialProps = async (appContext) => {
    // 调用页面的getInitialProps,避免页面的生命周期失效
    const appProps = await App.getInitialProps(appContext);
    const ctx = appContext.ctx;
    const auth = withSSRContext(ctx).Auth as typeof Auth

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

    // 合并返回所有props
    return { ...appProps, user }
}

方案2:封装公共鉴权HOC(适合混合SSG/SSR的场景)

如果你的项目用到大量静态生成页面,不想因为getInitialProps禁用全站静态优化,可以封装一个通用的鉴权方法,在需要用户信息的页面级getServerSideProps中调用即可,避免重复编写用户获取逻辑。

补充说明

如果需要在客户端侧随时访问用户信息,也可以搭配React Context全局存储user状态,在根组件挂载时调用Auth.currentAuthenticatedUser()获取用户信息存入Context,更适合客户端交互多的场景。

内容的提问来源于stack exchange,提问作者Paul Bradbury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 15:36:04