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.41k stars 2.11k forks source link

@aws-amplify/adapter-nextjs 1.1.5 introduce error compiling in Next.js 14.2.4 #13515

Closed RodrigoTomeES closed 2 months ago

RodrigoTomeES commented 2 months ago

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication, GraphQL API

Amplify Version

v6

Amplify Categories

auth, api

Backend

Amplify CLI

Environment information

``` # Put output below this line System: OS: macOS 14.5 CPU: (10) arm64 Apple M2 Pro Memory: 251.55 MB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 20.10.0 - ~/.nvm/versions/node/v20.10.0/bin/node Yarn: 1.22.19 - ~/.nvm/versions/node/v20.10.0/bin/yarn npm: 10.2.3 - ~/.nvm/versions/node/v20.10.0/bin/npm pnpm: 8.9.2 - ~/.nvm/versions/node/v20.10.0/bin/pnpm bun: 1.1.13 - ~/.bun/bin/bun Browsers: Chrome: 126.0.6478.62 Safari: 17.5 Safari Technology Preview: 17.4 npmPackages: @ampproject/toolbox-optimizer: undefined () @aws-amplify/adapter-nextjs: 1.1.4 => 1.1.4 @aws-amplify/adapter-nextjs/api: undefined () @aws-amplify/adapter-nextjs/data: undefined () @aws-amplify/cli: 12.12.2 => 12.12.2 @babel/core: undefined () @babel/runtime: 7.22.5 @edge-runtime/cookies: 4.1.1 @edge-runtime/ponyfill: 2.4.2 @edge-runtime/primitives: 4.1.0 @hapi/accept: undefined () @hookform/resolvers: 3.6.0 => 3.6.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/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/valibot: 1.0.0 @hookform/resolvers/vest: 1.0.0 @hookform/resolvers/yup: 1.0.0 @hookform/resolvers/zod: 1.0.0 @mswjs/interceptors: undefined () @napi-rs/triples: undefined () @next/font: undefined () @opentelemetry/api: undefined () @radix-ui/react-accordion: 1.1.2 => 1.1.2 @radix-ui/react-avatar: 1.0.4 => 1.0.4 @radix-ui/react-checkbox: 1.0.4 => 1.0.4 @radix-ui/react-dialog: 1.0.5 => 1.0.5 @radix-ui/react-dropdown-menu: 2.0.6 => 2.0.6 @radix-ui/react-icons: 1.3.0 => 1.3.0 @radix-ui/react-label: 2.0.2 => 2.0.2 @radix-ui/react-popover: 1.0.7 => 1.0.7 @radix-ui/react-progress: 1.0.3 => 1.0.3 @radix-ui/react-radio-group: 1.1.3 => 1.1.3 @radix-ui/react-select: 2.0.0 => 2.0.0 @radix-ui/react-separator: 1.0.3 => 1.0.3 @radix-ui/react-slot: 1.0.2 => 1.0.2 @radix-ui/react-tabs: 1.0.4 => 1.0.4 @tanstack/react-table: 8.17.3 => 8.17.3 @total-typescript/ts-reset: 0.5.1 => 0.5.1 @types/node: 20.14.5 => 20.14.5 (20.11.25) @types/react: 18.3.3 => 18.3.3 (18.3.1) @types/react-dom: 18.3.0 => 18.3.0 @vercel/nft: undefined () @vercel/og: 0.6.2 acorn: undefined () amphtml-validator: undefined () anser: undefined () arg: undefined () assert: undefined () async-retry: undefined () async-sema: undefined () autoprefixer: 10.4.19 => 10.4.19 aws-amplify: 6.0.29 => 6.0.29 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 () babel-packages: undefined () browserify-zlib: undefined () browserslist: undefined () buffer: undefined () bytes: undefined () ci-info: undefined () class-variance-authority: 0.7.0 => 0.7.0 cli-select: undefined () client-only: 0.0.1 clsx: 2.1.1 => 2.1.1 (2.0.0) cmdk: 1.0.0 => 1.0.0 commander: undefined () comment-json: undefined () compression: undefined () conf: undefined () constants-browserify: undefined () content-disposition: undefined () content-type: undefined () cookie: undefined () cross-env: 7.0.3 => 7.0.3 cross-spawn: undefined () crypto-browserify: undefined () css.escape: undefined () data-uri-to-buffer: undefined () debug: undefined () devalue: undefined () domain-browser: undefined () edge-runtime: undefined () eslint: 8.57.0 => 8.57.0 eslint-config-next: 14.2.4 => 14.2.4 events: undefined () find-cache-dir: undefined () find-up: undefined () fresh: undefined () get-orientation: undefined () glob: undefined () gzip-size: undefined () http-proxy: undefined () http-proxy-agent: undefined () https-browserify: undefined () https-proxy-agent: undefined () icss-utils: undefined () ignore-loader: undefined () image-size: undefined () is-animated: undefined () is-docker: undefined () is-wsl: undefined () jest-worker: undefined () json5: undefined () jsonwebtoken: undefined () 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 () next: 14.2.4 => 14.2.4 next-themes: 0.3.0 => 0.3.0 node-fetch: undefined () node-html-parser: undefined () ora: undefined () os-browserify: undefined () p-limit: undefined () path-browserify: undefined () picomatch: undefined () platform: undefined () postcss: 8.4.38 => 8.4.38 (8.4.31) postcss-flexbugs-fixes: undefined () postcss-functions: 4.0.2 => 4.0.2 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.3.2 => 3.3.2 process: undefined () punycode: undefined () querystring-es3: undefined () raw-body: undefined () react: 18.3.1 => 18.3.1 react-builtin: undefined () react-dom: 18.3.1 => 18.3.1 react-dom-builtin: undefined () react-dom-experimental-builtin: undefined () react-experimental-builtin: undefined () react-hook-form: 7.52.0 => 7.52.0 react-is: 18.2.0 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 () 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 setimmediate: undefined () shadcn-ui: 0.8.0 => 0.8.0 shell-quote: undefined () sonner: 1.5.0 => 1.5.0 source-map: undefined () source-map08: undefined () stacktrace-parser: undefined () stream-browserify: undefined () stream-http: undefined () string-hash: undefined () string_decoder: undefined () strip-ansi: undefined () superstruct: undefined () tailwind-merge: 2.3.0 => 2.3.0 tailwindcss: 3.4.4 => 3.4.4 tailwindcss-animate: 1.0.7 => 1.0.7 tar: undefined () terser: undefined () text-table: undefined () timers-browserify: undefined () tty-browserify: undefined () typescript: 5.4.5 => 5.4.5 ua-parser-js: undefined () unistore: undefined () util: undefined () vm-browserify: undefined () watchpack: undefined () web-vitals: undefined () webpack: undefined () webpack-sources: undefined () ws: undefined () zod: 3.23.8 => 3.23.8 (, 3.22.4) npmGlobalPackages: corepack: 0.22.0 npm: 10.2.3 vercel: 33.0.1 ```

Describe the bug

After upgrade the package @aws-amplify/adapter-nextjs 1.1.4 to 1.1.5 we experimented this error when building the app:

We are using Bun

$ next build
  ▲ Next.js 14.2.4

   Creating an optimized production build ...
Failed to compile.

./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/createServerRunnerForAPI.mjs
Attempted import error: 'parseAmplifyConfig' is not exported from '@aws-amplify/core/internals/utils' (imported as 'parseAmplifyConfig').

Import trace for requested module:
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/createServerRunnerForAPI.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/index.mjs
./lib/fetch/utils.ts
./app/[client]/layout.tsx

./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
Attempted import error: 'parseAmplifyConfig' is not exported from '@aws-amplify/core/internals/utils' (imported as 'parseAmplifyConfig').

Import trace for requested module:
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/index.mjs
./lib/fetch/utils.ts
./app/[client]/layout.tsx

./node_modules/@aws-amplify/adapter-nextjs/dist/esm/createServerRunner.mjs
Attempted import error: 'parseAmplifyConfig' is not exported from '@aws-amplify/core/internals/utils' (imported as 'parseAmplifyConfig').

Import trace for requested module:
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/createServerRunner.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/index.mjs
./lib/fetch/utils.ts
./app/[client]/layout.tsx

> Build failed because of webpack errors
error: script "build" exited with code 1

Expected behavior

Compile without errors

Reproduction steps

We tried to make a minimal reproduction but we have not been able to achieve it and the code is not public

Code Snippet

The file with the issue

// /lib/fetch/utils.ts
import { generateServerClientUsingCookies } from '@aws-amplify/adapter-nextjs/api';
import amplifyConfig from '@/lib/aws-exports';
import { cookies, headers } from 'next/headers';
import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import { fetchAuthSession, fetchUserAttributes } from 'aws-amplify/auth/server';
import { getLocale } from '../locale';

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

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

export async function isUserAdmin() {
  try {
    const user = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: async (ctx) => {
        return await fetchAuthSession(ctx);
      },
    });

    const group = (user.tokens?.accessToken.payload['cognito:groups'] as string[])?.[0];

    if (group === 'admin') {
      return true;
    }

    return false;
  } catch (error: any) {
    throw new Error(`Error while fetching user data: ${error?.message ?? '__MISSING_ERROR_MESSAGE__'}`);
  }
}

export async function getUser() {
  let user = null;
  try {
    user = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: async (ctx) => {
        return await fetchAuthSession(ctx);
      },
    });
  } catch (error: any) {
    throw new Error(`Error while fetching user data: ${error?.message ?? '__MISSING_ERROR_MESSAGE__'}`);
  }

  return user;
}

export async function getUserAttributes() {
  try {
    const userAttributes = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: async (ctx) => {
        return await fetchUserAttributes(ctx);
      },
    });
    return userAttributes;
  } catch (error: any) {
    throw new Error(`Error while fetching user attributes: ${error?.message ?? '__MISSING_ERROR_MESSAGE__'}}`);
  }
}

// for now we are going to assume one group per user
export async function getUserGroup() {
  const user = await getUser();
  const cognitoGroups = user.tokens?.accessToken.payload['cognito:groups'] as string[];
  if (!cognitoGroups || cognitoGroups.length === 0) {
    throw new Error('User has no groups');
  }

  let group = cognitoGroups[0] as string;

  // if the user is admin we return the client that is in view
  if (group === 'admin') {
    const urlString = headers().get('referer');

    if (!urlString || !URL.canParse(urlString)) return group;

    // Replace with parse once it is available in all browsers
    // @see https://caniuse.com/mdn-api_url_parse_static
    const url = new URL(urlString);

    if (url?.pathname?.split('/').length >= 2) {
      group = url.pathname.split('/')[1]!;
    }
  }

  return group;
}

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

Maybe can be related with issue #13514

HuiSF commented 2 months ago

Hi @RodrigoTomeES sorry that you encountered this issue. You can resolve this issue by upgrading both aws-amplify and @aws-amplify/adapter-nextjs package to the latest versions.

RodrigoTomeES commented 2 months ago

@HuiSF hi, I tried it but it doesn't work I receive both errors together. The error of aws-amplify and the error of nextjs-adapter package

HuiSF commented 2 months ago

Hi @RodrigoTomeES I just tried using bun to create a new Next.js app, with installing

"@aws-amplify/adapter-nextjs": "^1.2.5",
"aws-amplify": "^6.3.7",

And using the createServerRunner and generateServerClientUsingCookies functions exported from @aws-amplify/adapter-nextjs packages.

bun next build compiled the source code without errors.

Could you try the following steps:

  1. remove node_modules, and .next directories (.next contains the Next app build cache)
  2. rerun bun install to install dependencies (make sure you have the latest versions specified for aws-amplify and @aws-amplfiy/adaper-nextjs)
  3. rerun bun next build
RodrigoTomeES commented 2 months ago

Hi @HuiSF I followed your steps but I had the same error:

$ next build
  ▲ Next.js 14.2.4

   Creating an optimized production build ...
Failed to compile.

./node_modules/@aws-amplify/data-schema-types/lib-esm/index.d.ts
Module not found: Can't resolve './builder'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/@aws-amplify/data-schema/dist/esm/runtime/index.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/generateClient.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/InternalAPI.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/index.mjs
./lib/fetch/utils.ts
./app/api/batchLine/route.ts

./node_modules/@aws-amplify/data-schema-types/lib-esm/index.d.ts
Module not found: Can't resolve './client'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/@aws-amplify/data-schema/dist/esm/runtime/index.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/generateClient.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/InternalAPI.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/index.mjs
./lib/fetch/utils.ts
./app/api/batchLine/route.ts

./node_modules/@aws-amplify/data-schema-types/lib-esm/index.d.ts
Module not found: Can't resolve './util'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/@aws-amplify/data-schema/dist/esm/runtime/index.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/generateClient.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/InternalAPI.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/index.mjs
./lib/fetch/utils.ts
./app/api/batchLine/route.ts

./node_modules/@aws-amplify/data-schema/dist/esm/runtime/index.mjs
export '__modelMeta__' (reexported as '__modelMeta__') was not found in '@aws-amplify/data-schema-types' (module has no exports)

Import trace for requested module:
./node_modules/@aws-amplify/data-schema/dist/esm/runtime/index.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/generateClient.mjs
./node_modules/@aws-amplify/api-graphql/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/InternalAPI.mjs
./node_modules/@aws-amplify/api/dist/esm/internals/index.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/generateServerClient.mjs
./node_modules/@aws-amplify/adapter-nextjs/dist/esm/api/index.mjs
./lib/fetch/utils.ts
./app/api/batchLine/route.ts

> Build failed because of webpack errors
error: script "build" exited with code 1

This is our package.json

{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "dev:turbo": "next dev --turbo",
    "debug": "cross-env NODE_OPTIONS='--inspect' next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "format": "prettier --ignore-path .gitignore --write .",
    "storybook": "storybook dev -p 6006",
    "build-storybook": "storybook build"
  },
  "dependencies": {
    "@aws-amplify/adapter-nextjs": "1.2.5",
    "@hookform/resolvers": "3.6.0",
    "@radix-ui/react-accordion": "1.1.2",
    "@radix-ui/react-avatar": "1.0.4",
    "@radix-ui/react-checkbox": "1.0.4",
    "@radix-ui/react-dialog": "1.0.5",
    "@radix-ui/react-dropdown-menu": "2.0.6",
    "@radix-ui/react-icons": "1.3.0",
    "@radix-ui/react-label": "2.0.2",
    "@radix-ui/react-popover": "1.0.7",
    "@radix-ui/react-progress": "1.0.3",
    "@radix-ui/react-radio-group": "1.1.3",
    "@radix-ui/react-select": "2.0.0",
    "@radix-ui/react-separator": "1.0.3",
    "@radix-ui/react-slot": "1.0.2",
    "@radix-ui/react-tabs": "1.0.4",
    "@tanstack/react-table": "8.17.3",
    "aws-amplify": "6.3.7",
    "class-variance-authority": "0.7.0",
    "clsx": "2.1.1",
    "cmdk": "1.0.0",
    "next": "14.2.4",
    "next-themes": "0.3.0",
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "react-hook-form": "7.52.0",
    "shadcn-ui": "0.8.0",
    "sonner": "1.5.0",
    "tailwind-merge": "2.3.0",
    "tailwindcss-animate": "1.0.7",
    "zod": "3.23.8"
  },
  "devDependencies": {
    "@aws-amplify/cli": "12.12.3",
    "@total-typescript/ts-reset": "0.5.1",
    "@types/node": "20.14.5",
    "@types/react": "18.3.3",
    "@types/react-dom": "18.3.0",
    "autoprefixer": "10.4.19",
    "cross-env": "7.0.3",
    "eslint": "8.57.0",
    "eslint-config-next": "14.2.4",
    "postcss": "8.4.38",
    "postcss-functions": "4.0.2",
    "prettier": "3.3.2",
    "tailwindcss": "3.4.4",
    "typescript": "5.4.5"
  }
}

@HuiSF in your test did you use the code snippet that I added to the issue?

HuiSF commented 2 months ago

Hi @RodrigoTomeES looking at this path ./node_modules/@aws-amplify/data-schema-types/lib-esm/index.d.ts this is from a very old version of the @aws-amplify/data-schema-types package while the newer version of the @aws-amplify/data-schema is pointing to ./node_modules/@aws-amplify/data-schema/dist/esm/runtime/index.mjs. It's likely bun has its own cache somewhere (sorry I'm not very familiar with bun's package manager)

Could you also try to remove package lock file, clear bun's cache and redo the steps mentioned above?

If it installs everything correctly, when you run bun pm ls --all, you should see the following:

├── @aws-amplify/adapter-nextjs@1.2.5
├── @aws-amplify/analytics@7.0.35
├── @aws-amplify/api@6.0.37
├── @aws-amplify/api-graphql@4.1.6
│   └── @aws-sdk/types@3.387.0
├── @aws-amplify/api-rest@4.0.35
├── @aws-amplify/auth@6.3.6
├── @aws-amplify/core@6.3.2
├── @aws-amplify/data-schema@1.3.2
├── @aws-amplify/data-schema-types@1.0.1
├── @aws-amplify/datastore@5.0.37
├── @aws-amplify/notifications@2.0.35
├── @aws-amplify/storage@6.4.6
├── aws-amplify@6.3.7
RodrigoTomeES commented 2 months ago

@HuiSF you are rigth, I need to remove bun.lockb to make it work, thanks!