aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.43k stars 2.13k forks source link

NextJS SSR not able to access User Session from call #9396

Closed dbhagen closed 2 years ago

dbhagen commented 2 years ago

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication, DataStore

Amplify Categories

auth

Environment information

``` ➜ npx envinfo --system --binaries --browsers --npmPackages --duplicates --npmGlobalPackages Need to install the following packages: envinfo Ok to proceed? (y) y System: OS: macOS 12.0.1 CPU: (8) arm64 Apple M1 Memory: 136.83 MB / 16.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node Yarn: 1.22.17 - /opt/homebrew/bin/yarn npm: 7.20.3 - ~/.nvm/versions/node/v14.17.0/bin/npm Watchman: 2021.12.06.00 - /opt/homebrew/bin/watchman Browsers: Brave Browser: 96.1.32.115 Chrome: 96.0.4664.110 Safari: 15.1 npmPackages: @ampproject/toolbox-optimizer: undefined () @aws-amplify/ui-react: ^2.1.5 => 2.1.5 @aws-amplify/ui-react-internal: undefined () @aws-amplify/ui-react-legacy: undefined () @babel/core: undefined () @peculiar/webcrypto: undefined () @vercel/nft: undefined () amphtml-validator: undefined () arg: undefined () async-retry: undefined () async-sema: undefined () aws-amplify: ^4.3.11 => 4.3.11 babel-packages: undefined () ci-info: undefined () cli-select: undefined () comment-json: undefined () compression: undefined () conf: undefined () content-disposition: undefined () content-type: undefined () cookie: undefined () cross-spawn: undefined () debug: undefined () devalue: undefined () escape-string-regexp: undefined () eslint: 8.5.0 => 8.5.0 eslint-config-next: 12.0.7 => 12.0.7 find-cache-dir: undefined () find-up: undefined () formdata-node: undefined () fresh: undefined () glob: undefined () gzip-size: undefined () http-proxy: undefined () icss-utils: undefined () ignore-loader: undefined () is-animated: undefined () is-docker: undefined () is-wsl: undefined () json5: undefined () jsonwebtoken: undefined () loader-utils: undefined () lodash.curry: undefined () lru-cache: undefined () micromatch: undefined () mini-css-extract-plugin: undefined () nanoid: undefined () native-url: undefined () neo-async: undefined () next: 12.0.7 => 12.0.7 node-libs-browser: undefined () ora: 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 () react: 17.0.2 => 17.0.2 react-dom: 17.0.2 => 17.0.2 react-server-dom-webpack: undefined () resolve-url-loader: undefined () sass-loader: undefined () schema-utils: undefined () semver: undefined () send: undefined () source-map: undefined () string-hash: undefined () strip-ansi: undefined () terser: undefined () text-table: undefined () ua-parser-js: undefined () unistore: undefined () uuid: undefined () web-streams-polyfill: undefined () web-vitals: undefined () webpack: undefined () webpack-sources: undefined () ws: undefined () npmGlobalPackages: @aws-amplify/cli: 7.6.4 npm: 7.20.3 ```

Describe the bug

Basic setup for an Auth project using multiple example projects. Using create-next-app and a basic Amplify project with basic auth enabled (check src/aws-exports.js). But when run, the server-side doesn't process user sessions. Check SSRuser output on index.js. If you run locally, the console also shows server-side output better.

Possibly related to:

  DataStore: {
    authModeStrategyType: AuthModeStrategyType.MULTI_AUTH
  },

Expected behavior

Expecting to see user data (ID, groups, etc).

Also potentially blocking DataSync from making calls. I'm seeing on another project:

DataStore - queryError User is unauthorized to query syncTestModel, some items could not be returned

Reproduction steps

npx create-next-app sample-amplify-nextjs-prj
cd sample-amplify-nextjs-prj
amplify pull --appId d1syzsctvrw57p --envName staging
yarn dev

Also can use:

git clone https://github.com/dbhagen/sample-amplify-nextjs-prj.git
cd sample-amplify-nextjs-prj
yarn dev

Code Snippet

// Put your code below this line.

Log output

``` // Put your logs below this line ```

aws-exports.js

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_cognito_identity_pool_id": "us-east-1:423984d2-75c7-4a90-9540-2a6a1f592375",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_abJatluGy",
    "aws_user_pools_web_client_id": "5hatpusfu1qjncc0e1svub4li6",
    "oauth": {},
    "aws_cognito_username_attributes": [
        "EMAIL"
    ],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": [
            "REQUIRES_LOWERCASE",
            "REQUIRES_NUMBERS",
            "REQUIRES_SYMBOLS",
            "REQUIRES_UPPERCASE"
        ]
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

export default awsmobile;

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

dbhagen commented 2 years ago

I played around with this a little more last night. When I console.log(SSR.Auth.user) I got NULL. when I called console.log(SSR.Auth.currentAuthenticatedUser()) I got the user session. When I called console.log(SSR.Auth.user) after currentAuthenticatedUser, it returns the user session. None of the above impacts Datastore trying to use USER_POOL to access data that does not have API access (Owner only)

EDIT: forgot the method I tested with was actually currentAuthenticatedUser

dbhagen commented 2 years ago

Might be related to #9179.

dbhagen commented 2 years ago

Updated https://github.com/dbhagen/sample-amplify-nextjs-prj/commit/53a87a4210c5915601e43f11bd296cd0da338a91 for example of the currentAuthenticatedUser() populating SSRuser.

dbhagen commented 2 years ago

And now sample TestModel code: https://github.com/dbhagen/sample-amplify-nextjs-prj/commit/657a4382dd5bdc42e1c7548b00d491261d2e1b35

chrisbonifacio commented 2 years ago

Hi @dbhagen 👋 it seems that you were able to get the user session on the server.

withSSRContext has to initialize Amplify on every request and while it populates the Credentials module based on the cookie from the request, I don't think it will automatically store a CognitoUser within the Auth module until currentAuthenticatedUser is called so that's probably why it has to be called first, and it is convention to rely on that async request from Cognito as seen in our doc examples anyway.

Going to close this issue. If you are still in need of assistance on this issue, please reply and I'll re-open. Otherwise, if you are experiencing a different issue, please open a new one with the related info.

github-actions[bot] commented 1 year ago

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels or Discussions for those types of questions.