1

I want to pass the user object to all pages in my next.js app. I am getting nothing written to the console or passed as a prop with the following code. The amplify part seems to be working.

// _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>
    )
}
Paul Bradbury
  • 85
  • 2
  • 10
  • 1
    Custom _app in Next.js does not support getServerSideProps and getStaticProps. Try to use getInitiapProps instead. – Nghiệp Jun 10 '21 at 11:37
  • I had a similar issue. getInitialProps will work but causes your app to server side render every page. https://nextjs.org/docs/advanced-features/custom-app#caveats – Stephan Du Toit Jun 10 '21 at 11:41

1 Answers1

0

Please read this part of the documentation for next.js

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

App currently does not support Next.js Data Fetching methods like getStaticProps or getServerSideProps.

So you must make some changes in your _app.js to achieve that.

you can find the solution here in this post: Next.js: Reduce data fetching and share data between pages

Hooman
  • 1,775
  • 1
  • 16
  • 15