alexrusin / nextjs-cognito-auth

14 stars 10 forks source link

How can I access current user in server component #1

Open akuntal opened 5 months ago

akuntal commented 5 months ago

Thank you for creating this brilliant repo! It has been incredibly helpful for me to understand how AWS Amplify works with Next.js.

While experimenting, I tried to retrieve the current user inside a server component or API. I created the following function for this purpose, but it throws an error:

⨯ Error: Cannot access Cognito.length on the server. You cannot dot into a client module from a server component. You can only pass the imported name through.
    at Object.get (/Users/alokkumar/Desktop/workspace/nextjs-cognito-auth/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:35:252553)
    at deepFreeze (/Users/alokkumar/Desktop/workspace/nextjs-cognito-auth/node_modules/@aws-amplify/core/dist/cjs/utils/deepFreeze.js:10:29)
    at deepFreeze (/Users/alokkumar/Desktop/workspace/nextjs-cognito-auth/node_modules/@aws-amplify/core/dist/cjs/utils/deepFreeze.js:12:36)
    at deepFreeze (/Users/alokkumar/Desktop/workspace/nextjs-cognito-auth/node_modules/@aws-amplify/core/dist/cjs/utils/deepFreeze.js:12:36)
    at AmplifyClass.configure (/Users/alokkumar/Desktop/workspace/nextjs-cognito-auth/node_modules/@aws-amplify/core/dist/cjs/singleton/Amplify.js:45:55)
    at createAmplifyServerContext (/Users/alokkumar/Desktop/workspace/nextjs-cognito-auth/node_modules/@aws-amplify/core/dist/cjs/adapterCore/serverContext/serverContext.js:18:13)

Here is the function


export async function getCurrentLoggedInUser(cookies: any) {
  return await runWithAmplifyServerContext({
    nextServerContext: {cookies: cookies},
    operation: async (contextSpec) => {
      try {
        const session = await fetchAuthSession(contextSpec);
        if (!session.tokens) {
          return;
        }
        const user = {
          ...(await getCurrentUser(contextSpec)),
          isAdmin: false,
        };
        const groups = session.tokens.accessToken.payload["cognito:groups"];
        // @ts-ignore
        user.isAdmin = Boolean(groups && groups.includes("Admins"));

        return user;
      } catch (error) {
        console.log(error);
      }
    },
  });
}