Jarrod Watts
Jarrod Watts

Reputation: 465

No current user - getServerSideProps Next JS and AWS Amplify

I'm trying to make an user-authenticated GraphQL request on the serverside in getServerSideProps using AWS Amplify and Next JS.

Users in my AWS Database can only access the data if they are the owner of the document.

The error I get from this is "No current user"... (which is being logged on the server). The problem is, that I need the user available in the getServerSideProps, so I can make the authenticated request happen.

Here is the code I currently have

index.tsx:

import Amplify, { API, graphqlOperation, withSSRContext } from "aws-amplify";
import config from "../aws-exports";
Amplify.configure({ ...config, ssr: true });

function Index({ bankAccounts }: { bankAccounts: BankAccount[] }) {

  return (
    ...stuff...
  );
}

index.tsx (getServerSideProps):

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { API } = withSSRContext(context);

  const result = (await API.graphql({
    query: listBankAccounts,
  })) as {
    data: ListBankAccountsQuery;
    errors: any[];
  };

  if (!result.errors) {
    return {
      props: {
        bankAccounts: result.data.listBankAccounts.items,
      },
    };
  }

  return {
    props: {
      bankAccounts: [],
    },
  };
};

I would greatly appreciate any help or advice you could offer!

Upvotes: 4

Views: 2133

Answers (1)

Gabe Hollombe
Gabe Hollombe

Reputation: 8067

It looks like you maybe just need to pass in authMode as well in your API.graphql call.

In the SSR Support for AWS Amplify blog post, inside the section titled Making an authenticated API request in getServerSideProps you'll see a code sample that looks like the following (note the addition of authMode below, which I don't see in your code sample above):

  const { API } = withSSRContext(context)
  let movieData
  try {
    movieData = await API.graphql({
      query: listMovies,
      authMode: "AMAZON_COGNITO_USER_POOLS"
    });
    console.log('movieData: ', movieData)
  } catch (err) {
    console.log("error fetching movies: ", err)
  }
  return {
    props: {
      movies: movieData ? movieData.data.listMovies.items : null
    }
  }
}```

Upvotes: 3

Related Questions