Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Amplify v6 and Next v14 getting UserUnAuthenticatedException: User needs to be authenticated to call this API when calling from Server Component. #13966

Open
3 tasks done
siphosenkosindhlovu opened this issue Oct 28, 2024 · 35 comments
Assignees
Labels
Auth Related to Auth components/category question General question

Comments

@siphosenkosindhlovu
Copy link

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

Amplify CLI

Environment information

# Put output below this line
 System:
    OS: Windows 11 10.0.22631
    CPU: (8) x64 Intel(R) Core(TM) i5-8350U CPU @ 1.70GHz
    Memory: 2.44 GB / 15.86 GB
  Binaries:
    Node: 22.8.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.22 - C:\Program Files\nodejs\yarn.CMD
    npm: 10.9.0 - C:\Program Files\nodejs\npm.CMD
    pnpm: 9.12.2 - C:\Program Files\nodejs\pnpm.CMD
  Browsers:
    Edge: Chromium (128.0.2739.63)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @ampproject/toolbox-optimizer:  undefined ()
    @aws-amplify/adapter-nextjs: ^1.2.22 => 1.2.22
    @aws-amplify/adapter-nextjs/api:  undefined ()
    @aws-amplify/adapter-nextjs/data:  undefined ()
    @aws-amplify/ui-react: ^6.1.2 => 6.1.2
    @aws-amplify/ui-react-internal:  undefined ()
    @babel/core:  undefined ()
    @babel/runtime:  7.22.5
    @chakra-ui/icons: ^2.1.1 => 2.1.1
    @chakra-ui/next-js: ^2.4.2 => 2.4.2
    @chakra-ui/react: 2.9 => 2.9.5
    @chakra-ui/system: ^2.5.1 => 2.6.2
    @chatscope/chat-ui-kit-react: ^1.10.1 => 1.10.1
    @chatscope/chat-ui-kit-styles: ^1.4.0 => 1.4.0
    @edge-runtime/cookies:  5.0.0
    @edge-runtime/ponyfill:  3.0.0
    @edge-runtime/primitives:  5.0.0
    @emotion/react: ^11.13.3 => 11.13.3
    @emotion/styled: ^11.13.0 => 11.13.0
    @hapi/accept:  undefined ()
    @hookform/resolvers: ^3.1.0 => 3.9.0
    @hookform/resolvers/ajv:  1.0.0
    @hookform/resolvers/arktype:  2.0.0
    @hookform/resolvers/class-validator:  1.0.0
    @hookform/resolvers/computed-types:  1.0.0
    @hookform/resolvers/effect-ts:  1.0.0
    @hookform/resolvers/fluentvalidation-ts:  1.0.0
    @hookform/resolvers/io-ts:  1.0.0
    @hookform/resolvers/joi:  1.0.0
    @hookform/resolvers/nope:  1.0.0
    @hookform/resolvers/superstruct:  1.0.0
    @hookform/resolvers/typanion:  1.0.0
    @hookform/resolvers/typebox:  1.0.0
    @hookform/resolvers/typeschema:  1.0.0
    @hookform/resolvers/valibot:  1.0.0
    @hookform/resolvers/vest:  1.0.0
    @hookform/resolvers/vine:  1.0.0
    @hookform/resolvers/yup:  1.0.0
    @hookform/resolvers/zod:  1.0.0
    @internationalized/date: ^3.2.0 => 3.5.1
    @mswjs/interceptors:  undefined ()
    @napi-rs/triples:  undefined ()
    @next/bundle-analyzer: ^14.0.4 => 14.0.4
    @next/font:  undefined ()
    @opentelemetry/api:  undefined ()
    @radix-ui/react-select: ^1.2.2 => 1.2.2
    @saas-ui/react: ^2.10.3 => 2.10.3
    @stripe/react-stripe-js: ^2.3.2 => 2.4.0
    @stripe/stripe-js: ^1.54.2 => 1.54.2
    @types/aws-lambda: ^8.10.128 => 8.10.145
    @types/google.maps: ^3.54.4 => 3.54.10
    @types/js-cookie: ^3.0.3 => 3.0.6 (2.2.7)
    @types/node: ^18.18.12 => 18.19.3
    @types/react: ^18.0.28 => 18.2.45
    @types/react-dom: ^18.2.19 => 18.2.19
    @types/react-icons: ^3.0.0 => 3.0.0
    @types/uuid: ^9.0.1 => 9.0.7
    @typescript-eslint/eslint-plugin: ^6.7.3 => 6.16.0
    @typescript-eslint/parser: ^6.7.3 => 6.16.0 (5.62.0)
    @uidotdev/usehooks: ^2.3.1 => 2.4.1
    @vercel/nft:  undefined ()
    @vercel/og:  0.6.3
    acorn:  undefined ()
    amphtml-validator:  undefined ()
    anser:  undefined ()
    arg:  undefined ()
    assert:  undefined ()
    async-retry:  undefined ()
    async-sema:  undefined ()
    aws-amplify: ^6.6.5 => 6.6.5
    aws-amplify/adapter-core:  undefined ()
    aws-amplify/analytics:  undefined ()
    aws-amplify/analytics/kinesis:  undefined ()
    aws-amplify/analytics/kinesis-firehose:  undefined ()
    aws-amplify/analytics/personalize:  undefined ()
    aws-amplify/analytics/pinpoint:  undefined ()
    aws-amplify/api:  undefined ()
    aws-amplify/api/server:  undefined ()
    aws-amplify/auth:  undefined ()
    aws-amplify/auth/cognito:  undefined ()
    aws-amplify/auth/cognito/server:  undefined ()
    aws-amplify/auth/enable-oauth-listener:  undefined ()
    aws-amplify/auth/server:  undefined ()
    aws-amplify/data:  undefined ()
    aws-amplify/data/server:  undefined ()
    aws-amplify/datastore:  undefined ()
    aws-amplify/in-app-messaging:  undefined ()
    aws-amplify/in-app-messaging/pinpoint:  undefined ()
    aws-amplify/push-notifications:  undefined ()
    aws-amplify/push-notifications/pinpoint:  undefined ()
    aws-amplify/storage:  undefined ()
    aws-amplify/storage/s3:  undefined ()
    aws-amplify/storage/s3/server:  undefined ()
    aws-amplify/storage/server:  undefined ()
    aws-amplify/utils:  undefined ()
    aws-sdk: ^2.1510.0 => 2.1526.0
    babel-packages:  undefined ()
    browserify-zlib:  undefined ()
    browserslist:  undefined ()
    buffer:  undefined ()
    bytes:  undefined ()
    ci-info:  undefined ()
    cli-select:  undefined ()
    client-only:  0.0.1
    commander:  undefined ()
    comment-json:  undefined ()
    compression:  undefined ()
    conf:  undefined ()
    constants-browserify:  undefined ()
    content-disposition:  undefined ()
    content-type:  undefined ()
    cookie: ^0.5.0 => undefined (0.7.2, 0.5.0, , 0.4.2)
    cross-env: ^7.0.3 => 7.0.3
    cross-spawn:  undefined ()
    crypto-browserify:  undefined ()
    css.escape:  undefined ()
    data-uri-to-buffer:  undefined ()
    date-fns: ^2.30.0 => 2.30.0
    date-fns-tz: ^2.0.0 => 2.0.0
    debug:  undefined ()
    devalue:  undefined ()
    domain-browser:  undefined ()
    dynamodb-streams-processor: ^1.0.2 => 1.0.2
    edge-runtime:  undefined ()
    eslint: ^8.50.0 => 8.56.0
    eslint-config-airbnb: ^19.0.4 => 19.0.4
    eslint-config-next: 13.2.1 => 13.2.1
    eslint-config-prettier: ^8.6.0 => 8.10.0
    eslint-config-xo: ^0.43.1 => 0.43.1
    eslint-config-xo-typescript: ^1.0.1 => 1.0.1
    eslint-plugin-import: ^2.25.3 => 2.29.1
    eslint-plugin-jsx-a11y: ^6.5.1 => 6.8.0
    eslint-plugin-prettier: ^5.0.0 => 5.1.2
    eslint-plugin-react: ^7.33.2 => 7.33.2
    eslint-plugin-react-hooks: ^4.3.0 => 4.6.0
    eslint-plugin-unused-imports: ^3.0.0 => 3.0.0
    events:  undefined ()
    find-cache-dir:  undefined ()
    find-up:  undefined ()
    framer-motion: ^9.1.7 => 9.1.7
    fresh:  undefined ()
    get-orientation:  undefined ()
    glob:  undefined ()
    graphql: ^16.6.0 => 16.8.1 (15.8.0)
    gzip-size:  undefined ()
    http-proxy:  undefined ()
    http-proxy-agent:  undefined ()
    https-browserify:  undefined ()
    https-proxy-agent:  undefined ()
    husky: ^8.0.3 => 8.0.3
    icss-utils:  undefined ()
    ignore-loader:  undefined ()
    image-size:  undefined ()
    ioredis: ^5.3.2 => 5.3.2
    is-animated:  undefined ()
    is-docker:  undefined ()
    is-wsl:  undefined ()
    jest-worker:  undefined ()
    js-cookie: ^3.0.5 => 3.0.5 (2.2.1)
    json5:  undefined ()
    jsonwebtoken:  undefined ()
    just-debounce-it: ^3.2.0 => 3.2.0
    loader-runner:  undefined ()
    loader-utils:  undefined ()
    lodash.curry:  undefined ()
    lru-cache:  undefined ()
    mini-css-extract-plugin:  undefined ()
    nanoid:  undefined ()
    native-url:  undefined ()
    neo-async:  undefined ()
    net: ^1.0.2 => 1.0.2
    next: ^14.2.15 => 14.2.15
    next-usequerystate: ^1.8.4 => 1.13.2
    next13-progressbar: ^1.2.1 => 1.2.2
    node-fetch: ^2.7.0 => 2.7.0 ()
    node-html-parser:  undefined ()
    ora:  undefined ()
    os-browserify:  undefined ()
    p-limit:  undefined ()
    path-browserify:  undefined ()
    picomatch:  undefined ()
    platform:  undefined ()
    postcss-flexbugs-fixes:  undefined ()
    postcss-modules-extract-imports:  undefined ()
    postcss-modules-local-by-default:  undefined ()
    postcss-modules-scope:  undefined ()
    postcss-modules-values:  undefined ()
    postcss-preset-env:  undefined ()
    postcss-safe-parser:  undefined ()
    postcss-scss:  undefined ()
    postcss-value-parser:  undefined ()
    prettier: 3.0.3 => 3.0.3
    process:  undefined ()
    punycode:  undefined ()
    querystring-es3:  undefined ()
    raw-body:  undefined ()
    rc-time-picker: ^3.7.3 => 3.7.3
    react: ^18.2.0 => 18.2.0 
    react-aria: ^3.25.0 => 3.31.0
    react-builtin:  undefined ()
    react-cookie: ^4.1.1 => 4.1.1
    react-dom: ^18.2.0 => 18.2.0
    react-dom-builtin:  undefined ()
    react-dom-experimental-builtin:  undefined ()
    react-easy-crop: ^4.7.4 => 4.7.5
    react-experimental-builtin:  undefined ()
    react-hook-form: ^7.43.2 => 7.53.1
    react-icons: ^4.10.1 => 4.12.0
    react-is:  18.2.0
    react-qr-code: ^2.0.12 => 2.0.12
    react-query: ^3.39.3 => 3.39.3
    react-refresh:  0.12.0
    react-server-dom-turbopack-builtin:  undefined ()
    react-server-dom-turbopack-experimental-builtin:  undefined ()
    react-server-dom-webpack-builtin:  undefined ()
    react-server-dom-webpack-experimental-builtin:  undefined ()
    react-stately: ^3.23.0 => 3.29.0
    react-time-picker: ^6.2.0 => 6.6.0
    react-use: ^17.4.0 => 17.4.2
    redis: ^4.6.7 => 4.6.12
    regenerator-runtime:  0.13.4
    sass-loader:  undefined ()
    scheduler-builtin:  undefined ()
    scheduler-experimental-builtin:  undefined ()
    schema-utils:  undefined ()
    semver:  undefined ()
    send:  undefined ()
    server-only: ^0.0.1 => 0.0.1
    setimmediate:  undefined ()
    shell-quote:  undefined ()
    simple-zustand-devtools: ^1.1.0 => 1.1.0
    slugify: ^1.6.6 => 1.6.6
    source-map:  undefined ()
    source-map08:  undefined ()
    stacktrace-parser:  undefined ()
    stream-browserify:  undefined ()
    stream-http:  undefined ()
    string-hash:  undefined ()
    string_decoder:  undefined ()
    strip-ansi:  undefined ()
    stripe: ^12.18.0 => 12.18.0
    superstruct:  undefined ()
    tar:  undefined ()
    terser:  undefined ()
    text-table:  undefined ()
    timers-browserify:  undefined ()
    tty-browserify:  undefined ()
    typescript: ^5.3.2 => 5.3.3
    ua-parser-js:  undefined ()
    unistore:  undefined ()
    urql: ^3.0.3 => 3.0.4
    urql-core:  undefined ()
    use-cookie-state: ^2.0.0 => 2.1.0
    util:  undefined ()
    uuid: ^9.0.0 => 9.0.1 (8.0.0)
    vm-browserify:  undefined ()
    watchpack:  undefined ()
    web-vitals:  undefined ()
    webpack:  undefined ()
    webpack-sources:  undefined ()
    ws:  undefined ()
    zod: ^3.21.4 => 3.22.4 ()
    zustand: ^4.3.6 => 4.4.7
  npmGlobalPackages:
    corepack: 0.29.3
    npm: 10.9.0

Describe the bug

Cannot use Amplify server api categories from NextJS server components on local computer, but works on deployment.

This code:

import { generateServerClientUsingCookies } from '@aws-amplify/adapter-nextjs/api'
import amplifyConfig from '@/src/amplifyconfiguration.json'
import { cookies } from 'next/headers'
import { createServerRunner } from '@aws-amplify/adapter-nextjs'
import { fetchAuthSession, getCurrentUser } from 'aws-amplify/auth/server'

export const cookieBasedClient = generateServerClientUsingCookies({
  config: amplifyConfig,
  cookies,
})

export const { runWithAmplifyServerContext } = createServerRunner({
  config: amplifyConfig,
})

export const getCurrentUserSSR = async () => {
  try {
    const currentUser = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: async (contextSpec) => {
        const session = await fetchAuthSession(contextSpec, {
          forceRefresh: true,
        })
        console.dir({ session })
        return await getCurrentUser(contextSpec)
      },
    })
    console.log({ currentUser })
    return currentUser
  } catch (e) {
    console.dir({ e })
  }
}

Throws this errror:

{
  e: UserUnAuthenticatedException: User needs to be authenticated to call this API.
      at assertAuthTokens (webpack-internal:///(rsc)/./node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/types.mjs:29:15)
      at getCurrentUser (webpack-internal:///(rsc)/./node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/internal/getCurrentUser.mjs:16:71)
      at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
      at async operation (webpack-internal:///(rsc)/./lib/utils/serverClient.ts:38:24)
      at async runWithAmplifyServerContext (webpack-internal:///(rsc)/./node_modules/aws-amplify/dist/esm/adapter-core/runWithAmplifyServerContext.mjs:25:24)
      at async getCurrentUserSSR (webpack-internal:///(rsc)/./lib/utils/serverClient.ts:27:29)
      at async VendorDashboardPage (webpack-internal:///(rsc)/./app/(site)/(vendor)/dashboard/vendor/page.tsx:28:25) {
    underlyingError: undefined,
    recoverySuggestion: 'Sign in before calling this API again.',
    constructor: [class AuthError extends AmplifyError]
  }
}

The session object undefined tokens and userSub fields event though the token is correctly set in the client and viewable on the server.

Important to note that everything works normally in client components.

Expected behavior

getCurrentUser() to return the credentials of the currently authenticated user.

Reproduction steps

  1. Setup an AWS Amplify Gen 1 project with Next 14 and AmplifyJS v6.
  2. Create a server component that uses the getCurrentUser() api category.
  3. Sign in and navigate to an the SSR page.

Code Snippet

// Put your code below this line.
import { generateServerClientUsingCookies } from '@aws-amplify/adapter-nextjs/api'
import amplifyConfig from '@/src/amplifyconfiguration.json'
import { cookies } from 'next/headers'
import { createServerRunner } from '@aws-amplify/adapter-nextjs'
import { fetchAuthSession, getCurrentUser } from 'aws-amplify/auth/server'

export const cookieBasedClient = generateServerClientUsingCookies({
  config: amplifyConfig,
  cookies,
})

export const { runWithAmplifyServerContext } = createServerRunner({
  config: amplifyConfig,
})

export const getCurrentUserSSR = async () => {
  try {
    const currentUser = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: async (contextSpec) => {
        const session = await fetchAuthSession(contextSpec, {
          forceRefresh: true,
        })
        console.dir({ session })
        return await getCurrentUser(contextSpec)
      },
    })
    console.log({ currentUser })
    return currentUser
  } catch (e) {
    console.dir({ e })
  }
}

Log output

// Put your logs below this line


aws-exports.js

No response

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

@github-actions github-actions bot added pending-triage Issue is pending triage pending-maintainer-response Issue is pending a response from the Amplify team. labels Oct 28, 2024
@siphosenkosindhlovu siphosenkosindhlovu changed the title Amplify v6 and Next v14 geeting UserUnAuthenticatedException: User needs to be authenticated to call this API when calling from Server Component. Amplify v6 and Next v14 getting UserUnAuthenticatedException: User needs to be authenticated to call this API when calling from Server Component. Oct 28, 2024
@austinjlaverty
Copy link

I'm experiencing the same, regardless if using cookies from next/headers or request+response in middleware

@cwomack cwomack added the Auth Related to Auth components/category label Oct 28, 2024
@cwomack cwomack self-assigned this Oct 28, 2024
@HuiSF
Copy link
Member

HuiSF commented Oct 28, 2024

Hi @siphosenkosindhlovu @austinjlaverty can you both confirm the following:

  • Have you configured Amplify on your client-side with Amplify.configure(config, { ssr: true })?
  • After signing in an end user, have the auth tokens been written into browser cookie store?

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Oct 28, 2024
@siphosenkosindhlovu
Copy link
Author

Hi @siphosenkosindhlovu @austinjlaverty can you both confirm the following:

  • Have you configured Amplify on your client-side with Amplify.configure(config, { ssr: true })?
  • After signing in an end user, have the auth tokens been written into browser cookie store?

Everything is configured on the front end. All cookies are present, I can long them in the Server Component. It even runs properly when deployed to AWS Amplify Hosting. But errors out when running locally witch fetchAuthSession(contextSpec) returning an undefined session.tokens field. Client side fetches work correctly through

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Oct 28, 2024
@austinjlaverty
Copy link

Hi @siphosenkosindhlovu @austinjlaverty can you both confirm the following:

  • Have you configured Amplify on your client-side with Amplify.configure(config, { ssr: true })?
  • After signing in an end user, have the auth tokens been written into browser cookie store?

Yep, setting ssr: true, and cookies are in browser storage. Client amplify APIs work when retrieving a user from these stored values.

This is the final piece of my migration from v5 to v6. Everything else is functioning great

@cwomack
Copy link
Member

cwomack commented Oct 28, 2024

@austinjlaverty and @siphosenkosindhlovu, can you share what shape of your client side config looks like? Feel free to redact/remove any sensitive ID's or informaiton.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Oct 28, 2024
@cwomack cwomack added question General question and removed pending-triage Issue is pending triage labels Oct 28, 2024
@siphosenkosindhlovu
Copy link
Author

siphosenkosindhlovu commented Oct 28, 2024

@austinjlaverty and @siphosenkosindhlovu, can you share what shape of your client side config looks like? Feel free to redact/remove any sensitive ID's or informaiton.

Here's what my amplifyconfiguration.json looks like:

{
  "aws_project_region": "us-east-1",
  "aws_cloud_logic_custom": [
    {
      "name": "stripe",
      "endpoint": "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/canary",
      "region": "us-east-1"
    }
  ],
  "aws_appsync_graphqlEndpoint": "https://xxxxxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql",
  "aws_appsync_region": "us-east-1",
  "aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
  "aws_appsync_apiKey": "xxxxxxxxxxxxxxxxxxxxx",
  "aws_cognito_identity_pool_id": "us-east-1:xxxxxxxxxxxxxxxxxxxxxxx",
  "aws_cognito_region": "us-east-1",
  "aws_user_pools_id": "us-east-xxxxxxxxxxxxxx",
  "aws_user_pools_web_client_id": "xxxxxxxxxxxxxxxxxx",
  "oauth": {},
  "aws_cognito_username_attributes": [
    "EMAIL"
  ],
  "aws_cognito_social_providers": [],
  "aws_cognito_signup_attributes": [
    "EMAIL"
  ],
  "aws_cognito_mfa_configuration": "OFF",
  "aws_cognito_mfa_types": [],
  "aws_cognito_password_protection_settings": {
    "passwordPolicyMinLength": 8,
    "passwordPolicyCharacters": [
      "REQUIRES_LOWERCASE",
      "REQUIRES_UPPERCASE",
      "REQUIRES_NUMBERS",
      "REQUIRES_SYMBOLS"
    ]
  },
  "aws_cognito_verification_mechanisms": [
    "EMAIL"
  ],
  "aws_user_files_s3_bucket": "xxxxxxxxxxxxxxxxxxxxxxxx",
  "aws_user_files_s3_bucket_region": "us-east-1"
}

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Oct 28, 2024
@austinjlaverty
Copy link

@austinjlaverty and @siphosenkosindhlovu, can you share what shape of your client side config looks like? Feel free to redact/remove any sensitive ID's or informaiton.

Here is mine:

import { type ResourcesConfig } from "aws-amplify";
import { APP_URL } from "@/utils/env";

export const AMPLIFY_CONFIG: ResourcesConfig = {
  Auth: {
    Cognito: {
      userPoolId: process.env.NEXT_PUBLIC_AMPLIFY_USER_POOL_ID!,
      userPoolClientId:
        process.env.NEXT_PUBLIC_AMPLIFY_USER_POOL_WEB_CLIENT_ID!,
      loginWith: {
        oauth: {
          domain: process.env.NEXT_PUBLIC_AMPLIFY_OAUTH_DOMAIN!,
          scopes: ["phone", "email", "profile", "openid"],
          redirectSignIn: [`${APP_URL}/login/verify`],
          redirectSignOut: [`${APP_URL}/`],
          responseType: "code",
        },
      },
    },
  },
};

@siphosenkosindhlovu
Copy link
Author

After some testing, it briefly worked when I'm behind a VPN (Cloudflare WARP in this instance) but stopped again.

@cwomack
Copy link
Member

cwomack commented Oct 31, 2024

@siphosenkosindhlovu want to circle back on this question from earlier. After signing in an end user, have the auth tokens been written into browser cookie store? Can you share the shape/values of the cookies in your cookie store?

@austinjlaverty, can you also share the shape/value of the cookies in your cookies store as well as clarify which API you're calling when you see this exception happening?

We're still trying to reproduce this on our side, but haven't been able to up to this point.

@cwomack cwomack added pending-community-response Issue is pending a response from the author or community. and removed pending-maintainer-response Issue is pending a response from the Amplify team. labels Oct 31, 2024
@austinjlaverty
Copy link

austinjlaverty commented Nov 1, 2024

@siphosenkosindhlovu want to circle back on this question from earlier. After signing in an end user, have the auth tokens been written into browser cookie store? Can you share the shape/values of the cookies in your cookie store?

@austinjlaverty, can you also share the shape/value of the cookies in your cookies store as well as clarify which API you're calling when you see this exception happening?

We're still trying to reproduce this on our side, but haven't been able to up to this point.

My app is only using Auth. It interfaces with a separate services API layer built on AWS.

I'm attempting to getCurrentUser() from aws-amplify/auth/server within the operation callback:

import { cookies } from "next/headers";
import { Amplify } from "aws-amplify";
import {
  fetchAuthSession,
  getCurrentUser as getCurrentAmplifyUser,
} from "aws-amplify/auth/server";
import { createServerRunner } from "@aws-amplify/adapter-nextjs";
import { AMPLIFY_CONFIG } from "./config";

Amplify.configure(AMPLIFY_CONFIG, {
  ssr: true,
});

export const { runWithAmplifyServerContext } = createServerRunner({
  config: AMPLIFY_CONFIG,
});

export async function getCurrentUser() {
  const user = await runWithAmplifyServerContext({
    nextServerContext: { cookies },
    operation: async (context) => {
      const session = await fetchAuthSession(context);

      console.log({ session, cookieStore: cookies() });

      //if (!session.tokens) return;
      
      const user = await getCurrentAmplifyUser(context);

      console.log({ user });

      return user;
    },
  });

  if (!user) {
    throw new Error("unauthenticated");
  }

  return user;
}

Upon successfully signing in from the client, cookies are present within the browser storage:

Screenshot 2024-11-01 133101

The same values are also present when logging the value of cookies() from the server:

{
  session: {
    tokens: undefined,
    credentials: undefined,
    identityId: undefined,
    userSub: undefined
  },
  cookieStore: RequestCookies {
    _parsed: Map(10) {
      'ajs_user_id' => [Object],
      'ajs_anonymous_id' => [Object],
      'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.LastAuthUser' => [Object],
      'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.accessToken' => [Object],
      'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.idToken' => [Object],
      'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.refreshToken' => [Object],
      'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.clockDrift' => [Object],
    },
  }
}

As a result, everything on the server (components, route handlers, middleware using request+response) all fail to retrieve the authenticated state. However, once the client initializes and invokes getCurrentUser() from aws-amplify/auth it successfully retrieves the logged in user, and the UI reflects this.

My setup is currently working locally and in production using v5.

Locally I'm based in SEA, but the AWS project is us-east-1. I have no idea if that helps or might influence any sort of edge case.

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Nov 1, 2024
@siphosenkosindhlovu
Copy link
Author

siphosenkosindhlovu commented Nov 1, 2024

@siphosenkosindhlovu want to circle back on this question from earlier. After signing in an end user, have the auth tokens been written into browser cookie store? Can you share the shape/values of the cookies in your cookie store?

@austinjlaverty, can you also share the shape/value of the cookies in your cookies store as well as clarify which API you're calling when you see this exception happening?

We're still trying to reproduce this on our side, but haven't been able to up to this point.

Yep, they're being written to the browser store. When I use Amplify auth client side, it correctly shows as authenticated, but doesn't for SSR like for @austinjlaverty.

Here's what's logged from the server:

{
  session: {
    tokens: undefined,
    credentials: {
      accessKeyId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      secretAccessKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      sessionToken: 'IQoJb3JpZ2luX2VjECgaCXVzLWVhc3QtMSJHMEUCIQDyo9FUB9zOMoZWkdGxOImS1CXC5y70hF/v1YD3/8AXMgIgJNXExtQwZVgtpk17v0JCpjojWmrlwFcecykZ1Gv2jFsq0gUIof//////////ARAEGgw0MDUwOTQ1OTIwNzgiDOZOrKKSwmGFZNJYviqmBawH0IO5k9afRoU7g6cFY1Flbzl3dbB3fNIddHGj3aCHMwG/ptBG+4kmEa0x6dvab1iWaePeJgjcHCl3XKDdHgoT9MboVvvJIYBtRKMydLvixKbeVB0uea3MT38bhKQFYnsUXf1a0CcNexJnQwYi9di6CkScW74p1+2CHZxOKqToWD0GmHf8VvoFcOortgZFfcabMsPOd3PMVvd1IRV5MCJQvx/HmvES9yejOi8KC7fUlbiCpdA9lBzEy3MhN7KKg45H6lggl4ljn8boJZUx12iPuEk3DEp3jhyuQC/5Vnfmr8ogRgNRtqct/OcZhb6PuFD9IuuIvf/x13goMpkKBM/U508dIH+SbubUdcDJR37p0dYwno8IatGDKtDTZHoIUs6UllmFmEnrmh+wv6eOrsYafKNYFs5tHGYiJvRxGWi0n3AAixsO09naB9KCMACXhoXgT4Osxre2Z8Pka0P7dmwjLNsiLRpQQAGL34hdxWhi39dT1kkZdjXnwRs44AAIP+Wj4JscIgbC/bAyYY5NQDQQIwLFKF4zaj0ucMNO3R0QeLj0AjFcqpyY4BMG0bugZTM7S0rGfidHmmSppUG5Yo8xm36D1ifK/mSYJLoh5cMtIxKnPkCeBceJDEU/04KX1ukaIkNLd0/5IzEKbvgMmym/odrdT3hCu1JIEEjn4QPLEYBqYeFoo1l0NwpJz2YsXpQifZbTy06XLShRbUQ3Ct7uQxaodOGphMiR86qJAQDTG+OK9vLh+J/z9MLb8Qr8T9duR8a63U6WG5mzuJIeJiZJCkU9SkhzsGpA0bCwndlqfufXHLe9MwxNC2xLFLXFevIvaTcMIC4RrjsM5wK5timN1h70LDw3DfnwSThdAQFgPjh+7iqAg+G73Mg3NzqU8CyLqS3N4TCNkZK5BjrdAuGR7mCDDIytlSPL8U2HVmfzHDnl29uQkHzl+plM79/X6DlCXBiHxMibOIGc4awCNeP5WMCdGgxh/hDl7qM5RQXEqApenmCHyZcNBQ0vxiZ/L6dkjbLFpP0mrwIEZhpPU+xpakniYN9v/g3yv1/00Ng6D0ZAsff/jE9FNRL8CjjNFz6bXSN+RIC2DHpyQykqHK/aAT7RMHwwR8G0CUcyJp4qYR0YmBcTbGicCSNI8MsRmF4zEIjhoGyPZNrUg3lOZEhE4PayQ8mfz4n0xhN692euDQm/f7w7rfDSId223481bTn6gNWJGYW8ZNemxNx0NqjiCGP0JX7/8MefTAuPsrxCyYDpuyQKPZhCF8xCaCgdxZgg3fAh+u0Yo2wTmk0FSzGwHqq9EANPAKUCuQGKNBkI5BZSGGaOVOiynsBkCO4/OrAA+QXq6j13wUL20aFhALOb/V4EWS7gD2ck/vQ=',
      expiration: 2024-11-01T08:51:41.000Z
    },
    identityId: 'us-east-1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    userSub: undefined
  },
  cookies: f {
    _parsed: Map(7) {
      'activeProfile' => [Object],
      'CognitoIdentityServiceProvider.xxxxxxxxxxxxxxxxxxxxxxxxxx.LastAuthUser' => [Object],
      'CognitoIdentityServiceProvider.xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.accessToken' => [Object],
      'CognitoIdentityServiceProvider.xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.idToken' => [Object],
      'CognitoIdentityServiceProvider.xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.refreshToken' => [Object],
      'CognitoIdentityServiceProvider.xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.signInDetails' => [Object],
      'CognitoIdentityServiceProvider.xxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.clockDrift' => [Object]
    },
    _headers: Headers {}
  }
}

And from the browser console:
image

It's only working when deployed to AWS Amplify.

@cwomack
Copy link
Member

cwomack commented Nov 1, 2024

@austinjlaverty and @siphosenkosindhlovu, greatly appreciate the detailed responses and follow up here. While we work on reproducing the issue on our side, are either of you able to provide a public, minimal sample repo or possibly invite to a private repo where this is happening?

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Nov 1, 2024
@cwomack
Copy link
Member

cwomack commented Nov 1, 2024

@austinjlaverty, is your app also only experiencing this locally (but not when deployed)?

@siphosenkosindhlovu
Copy link
Author

siphosenkosindhlovu commented Nov 12, 2024

@siphosenkosindhlovu @austinjlaverty do u both see any network error before tokens & userSub becomes undefined? or this is happening from beginning.?

I get the errors after running fetchAuthSession() which returns an object with missing tokens and userSub and before getCurrentUser(), which I'm guessing failes because there is no user in the session.

Update: No longer getting a network error but the same auth error on Ubuntu WSL. And again, everything works with Docker on the same computer, I guess I'll work that way for now.

@cwomack
Copy link
Member

cwomack commented Nov 14, 2024

@siphosenkosindhlovu, thanks for following up. Can you see if upgrading to the latest version of Amplify (currently v6.8.2) to see if the issue is resolved? That should resolve any issues that would be the result of a network error, but I'm curious to see if the Auth errors persist when upgrading as well.

If it's working in Docker, but not WSL, it may be something tied to support from the WSL side (rather than Amplify).

@cwomack cwomack added pending-community-response Issue is pending a response from the author or community. and removed pending-maintainer-response Issue is pending a response from the Amplify team. labels Nov 14, 2024
@siphosenkosindhlovu
Copy link
Author

@cwomack updated to the latest version of Amplify and it's still the same. Doesn't work on native Windows and WSL.

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Nov 15, 2024
@ashika112
Copy link
Member

@siphosenkosindhlovu the auth error will happen if tokens & userSub is undefined. You want to trace the cause for that. I dont think it is happening directly because of Amplify. Can you check what is happening the storage throughout the flow?

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Nov 15, 2024
@siphosenkosindhlovu
Copy link
Author

@cwomack @ashika112 tried on another PC connected to the same network and I'm getting the same errors. I can see the cookies when I console log them, but fetchAuthSession always returns returns undefined tokens. Not sure how to trace the problem further than that.

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Nov 16, 2024
@cwomack
Copy link
Member

cwomack commented Nov 18, 2024

@siphosenkosindhlovu, do you have any type of global install on the WSL that could be using a different version of Next.JS? The stack trace shows the following:

underlyingError: TypeError: fetch failed
        at node:internal/deps/undici/undici:13392:13

This looks like it could be related to the following from the Vercel repo - vercel/next.js#48744

@cwomack cwomack added the pending-community-response Issue is pending a response from the author or community. label Nov 18, 2024
@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Nov 18, 2024
@siphosenkosindhlovu
Copy link
Author

@cwomack nope. I don't have any global installs on WSL except for npm itself and corepack

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Nov 19, 2024
@cwomack
Copy link
Member

cwomack commented Nov 20, 2024

@siphosenkosindhlovu, thanks for confirming. The more we look into this, the more I'm curious if you see any similar behavior to what the intended fix was from the Next.js team as seen in this PR where they needed to unset the header if the content-length = 0.

Can you inspect your network requests in the WSL environment to see what the content-length is when this issue happens?

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Nov 20, 2024
@cwomack cwomack added the pending-community-response Issue is pending a response from the author or community. label Nov 20, 2024
@cwomack
Copy link
Member

cwomack commented Nov 26, 2024

@siphosenkosindhlovu, wanted ping you again to see if you saw the above comment and had a chance to look into the content-length. Let us know if this is still blocking you!

@austinjlaverty
Copy link

austinjlaverty commented Nov 27, 2024

Is v6 that fundamentally different from v5 that the environment would cause such a strange and silent failure?

I also work locally Windows and WSL, and have had to downgrade back to v5 so I can remain productive.

There are no errors getting thrown to trace. I suppose I can dig into the content length of the amplify calls, but I'm not convinced.

This is an app in production and connected to dozens of endpoints. Surely they would also be running into the same issue using same fetch mechanism?

While we used to see that undici issue surface in our vercel logs in the past, this has long since been resolved with next version upgrades (an was never such a consistent or local issue)

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Nov 27, 2024
@HuiSF
Copy link
Member

HuiSF commented Dec 2, 2024

Hi @austinjlaverty

Is v6 that fundamentally different from v5 that the environment would cause such a strange and silent failure?

One difference between v5 and v6 is that v6 uses fetch API as the HTTP client instead of Axios used by v5. The library uses the fetch API as is without any kind of customization.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Dec 2, 2024
@austinjlaverty
Copy link

austinjlaverty commented Dec 4, 2024

Based on the suggestion of siphosenkosindhlovu, I tried using Docker to run the local dev server, and now everything works flawlessly. Looks like I'll also be doing this for now

Whatever the issue is, it seems to have started with v6 and is isolated to WSL environments (haven't confirmed with windows node)

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Dec 4, 2024
@HuiSF
Copy link
Member

HuiSF commented Dec 4, 2024

Thanks for the follow up @austinjlaverty and glad to hear that you found a way to proceed. As I mentioned earlier, Amplify v6 uses the fetch API, it depends on the environment to provide its implementation and the underlying error is out of the control of the library.

I will try to find a Windows environment to run some testing see if I can reproduce this.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Auth Related to Auth components/category question General question
Projects
None yet
Development

No branches or pull requests

8 participants