In _app.tsx of Next.js, the user prop will not be passed

I am trying to pass the user object to all pages in my next.js app and encountering an issue. Despite having working amplify code, I am unable to see anything in the console or passed as a prop with the current implementation.

// _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>
    )
}

Answer №1

Make sure to review the following section of the next.js documentation

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

Note that the App component does not currently support Next.js Data Fetching methods such as getStaticProps or getServerSideProps.

To overcome this limitation, adjustments need to be made in your _app.js.

For a detailed guide on resolving this issue, refer to the following resource: Next.js: Reduce data fetching and share data between pages

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing the next link href based on a specific condition

The following code snippet is causing me some trouble: <a onClick={() => { if (fortype === "user") { if (rd.track !== null) { router.push({ pathname: `/tracks/${rd.track._id}`, query: { fr ...

Utilizing Djoser in Django Rest Framework to bypass Facebook and Google authentication, integrated with Next.js+React for a seamless frontend experience

My approach involved using Djoser to manage essential user authentication functionalities in Django Rest Framework. To explore its social auth endpoint, I referred to its documentation for guidance. Initially, I incorporated a redirect_uri into the endpoin ...

Workspace watch mode does not update Typescript definitions

Greetings to all who are reading this, I have created a React micro-frontend project using SPA v5.9, Webpack v5.75, Babel-loader v9.1, Ts-loader v9.4, and Yarn workspace v3.5. The project structure is very basic: Root SPA => Package Root Application S ...

Typescript excels at gracefully handling cases where an element is not found

While working with Typescript-Protractor Jasmine, I encountered an issue where the test case (the 'it' block) is not failing when an element is not found. Instead, it shows an UnhandledPromiseRejectionWarning but still marks the script as passed. ...

What is the trick to accessing an object's key and value when you are unsure of the object's

Currently, I am in the process of constructing a React component that is designed to receive an array of objects. However, I have encountered a question: Is there a way for me to retrieve both the key and value of an object within the map function without ...

Can an App be duplicated from Chrome sources even if it displays all files except for the package.json?

I recently came across a React platform that I would like to dissect in order to gain a deeper understanding of it and potentially redesign it for a future project. Though the platform seems to have all the necessary files, I am unsure if I may be missing ...

At the beginning of the project, there is an issue with loading certain tailwind class names from a ternary operator in React, causing them not

I'm experiencing an issue where certain Tailwind CSS class names are not loading when they come from a React property. I have attached a video demonstrating the error and would like to find a solution to ensure that the colors load even when using a t ...

Why is it that Eslint Plugins are present locally, but I am unable to compile them on the server?

The ESlint command is encountering an error on the server during the build process: ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin". However, everything is running smoothly on the local environment. Since there is no global eslint ...

Issues arise when trying to implement Angular class and it does

I'm currently facing some challenges using classes in Angular to simplify my coding process. So far, I haven't been able to get it to work properly. Below is the code snippet I'm working with and the error message that pops up: import { Wiz ...

Sort the array by the elements in a separate array

Here is a filters array with three values: serviceCode1, serviceCode2, and serviceCode3. ['serviceCode1', 'serviceCode2', 'serviceCode3'] I have another array with approximately 78 records that I want to filter based on the a ...

Using RxJs to apply a `filter` to an Array of Observable<T>, and emitting the value as soon as it meets a certain condition

Currently working on an application built with Angular2 in TypeScript, utilizing rxjs 5. Edit: Just to clarify, I am still relatively new to the Rx library and looking for the best practices. I did try to find some answers in the documentation before seek ...

Steer clear of making changes to a JavaScript array

Here is my code snippet: let traces = { ref: null, min: null, max: null, avg: null }; let learning = { "Application": "b3", "t": [ { "d": 2, "BinaryType": "Current" }, { "d": 3, ...

What is the process for connecting a form to a model in Angular 6 using reactive forms?

In the time before angular 6, my approach involved utilizing [(ngModel)] to establish a direct binding between my form field and the model. However, this method is now considered deprecated (unusable with reactive forms) and I find myself at a loss on how ...

Stopping a recurring setTimeout using an API request: What's the solution?

I have a NextJS application that runs a recursive setTimeout when the server is started. I am looking to create an API endpoint that can control this loop, allowing me to start and stop it as needed in a production environment. This loop specifically proce ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

Access to property 'foo' is restricted to an instance of the 'Foo' class and can only be accessed within instances of 'Foo'

In my Typescript code, I encountered an error with the line child._moveDeltaX(delta). The error message reads: ERROR: Property '_moveDeltaX' is protected and only accesible through an instance of class 'Container' INFO: (me ...

Not verifying the argument type in Typescript makes the function generic in nature

I was initially under the impression that TypeScript would throw an error due to passing the incorrect number of elements in EntryPoints, but surprisingly, no error occurred. function createContext<T>(defaultValue: T): T[] { return [defaultValue] ...

Automatically resetting the Redux toolkit store when navigating between pages in Next.js

I am a new Next user who has been using Redux with React for a while. However, I encountered many challenges when trying to integrate Redux with Next. I have decided to move on from this solution. store.js import { configureStore } from '@reduxjs/to ...

Implementing Facebook Javascript SDK to enable login and trigger re-authentication using React Web and Typescript within a component

As a newcomer to stack overflow, I welcome any suggestions on how I can improve my question. I'm in need of guidance concerning logging a user into facebook and requiring them to authenticate their profile or select another profile manually, rather t ...

Errors in TypeScript Compiler for using react-bootstrap in SPFx project

After setting up an SPFX Project with Yeoman generator and including react-bootstrap as a dependency, I encountered errors when using react-bootstrap components and running gulp serve. The error messages are as follows; does anyone have any solutions to ...