Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 857
Jarrod Watts Avatar asked Oct 30 '25 22:10

Jarrod Watts


1 Answers

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
    }
  }
}```
like image 58
Gabe Hollombe Avatar answered Nov 02 '25 12:11

Gabe Hollombe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!