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

RangeError: Maximum call stack size exceeded on NextJS v15 Middleware #14245

Open
3 tasks done
CarlWangMK opened this issue Feb 25, 2025 · 1 comment
Open
3 tasks done
Labels
Core Related to core Amplify issues Next.js pending-triage Issue is pending triage

Comments

@CarlWangMK
Copy link

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

None

Environment information

  System:
    OS: Windows 10 10.0.19045
    CPU: (12) x64 12th Gen Intel(R) Core(TM) i5-1235U
    Memory: 2.57 GB / 15.64 GB
  Binaries:
    Node: 22.12.0 - C:\Program Files\nodejs\node.EXE 
    npm: 11.0.0 - C:\Program Files\nodejs\npm.CMD    
  Browsers:
    Edge: Chromium (131.0.2903.112)
    Internet Explorer: 11.0.19041.4355
  npmPackages:
    @ampproject/toolbox-optimizer:  undefined ()     
    @aws-amplify/adapter-nextjs: ^1.0.27 => 1.0.27   
    @aws-amplify/adapter-nextjs/api:  undefined ()   
    @aws-amplify/adapter-nextjs/data:  undefined ()  
    @babel/core:  undefined ()
    @babel/runtime:  7.22.5 
    @edge-runtime/cookies:  6.0.0 
    @edge-runtime/ponyfill:  4.0.0 
    @edge-runtime/primitives:  6.0.0 
    @hapi/accept:  undefined ()
    @heroicons/react: ^2.1.3 => 2.1.3 
    @mswjs/interceptors:  undefined ()
    @napi-rs/triples:  undefined ()
    @next/font:  undefined ()
    @opentelemetry/api:  undefined ()
    @tailwindcss/forms: ^0.5.7 => 0.5.7
    @types/node: ^20 => 20.12.2
    @types/react: ^18 => 18.2.73
    @types/react-dom: ^18 => 18.2.23
    @vercel/nft:  undefined ()
    @vercel/og:  0.6.4
    acorn:  undefined ()
    amphtml-validator:  undefined ()
    anser:  undefined ()
    assert:  undefined ()
    async-retry:  undefined ()
    async-sema:  undefined ()
    autoprefixer: ^10.0.1 => 10.4.19
    aws-amplify: ^6.0.27 => 6.0.27
    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 ()
    cli-select:  undefined ()
    client-only:  0.0.1
    clsx: ^2.1.0 => 2.1.0
    commander:  undefined ()
    comment-json:  undefined ()
    compression:  undefined ()
    conf:  undefined ()
    constants-browserify:  undefined ()
    content-disposition:  undefined ()
    content-type:  undefined ()
    cookie:  undefined ()
    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 => 8.57.0
    eslint-config-next: 14.1.4 => 14.1.4
    events:  undefined ()
    find-up:  undefined ()
    fresh:  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.1.4 => 15.1.7
    node-fetch:  undefined ()
    node-html-parser:  undefined ()
    ora:  undefined ()
    os-browserify:  undefined ()
    p-limit:  undefined ()
    p-queue:  undefined ()
    path-browserify:  undefined ()
    path-to-regexp:  undefined ()
    picomatch:  undefined ()
    platform:  undefined ()
    postcss: ^8 => 8.4.38 (8.4.31)
    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 ()
    process:  undefined ()
    punycode:  undefined ()
    querystring-es3:  undefined ()
    raw-body:  undefined ()
    react: ^18 => 18.2.0
    react-builtin:  undefined ()
    react-dom: ^18 => 18.2.0
    react-dom-builtin:  undefined ()
    react-dom-experimental-builtin:  undefined ()
    react-experimental-builtin:  undefined ()
    react-is:  19.0.0-rc-65e06cb7-20241218
    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 ()
    shell-quote:  undefined ()
    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 ()
    tailwindcss: ^3.3.0 => 3.4.3
    tar:  undefined ()
    terser:  undefined ()
    text-table:  undefined ()
    timers-browserify:  undefined ()
    tty-browserify:  undefined ()
    typescript: ^5 => 5.4.3
    ua-parser-js:  undefined ()
    unistore:  undefined ()
    util:  undefined ()
    vm-browserify:  undefined ()
    watchpack:  undefined ()
    web-vitals:  undefined ()
    webpack:  undefined ()
    webpack-sources:  undefined ()
    ws:  undefined ()
    zod:  undefined ()
    zod-validation-error:  undefined ()
  npmGlobalPackages:
    npm: 11.0.0

Describe the bug

Image

This issue only occurs if middleware.ts in the src directory is calling runWithAmplifyServerContext() in an async context. In the middleware function, as long as runWithAmplifyServerContext() is not executed, this error will not happen.

Expected behavior

NextJS app compiles frontend without displaying error

Reproduction steps

  1. Git clone this repository: https://github.com/alexrusin/nextjs-cognito-auth (used this repository as a reference while implementing cognito authentication and authorization, same issue will occur. Same issue happens on the repository I'm working on)
  2. Update NextJS to latest version 15.1.7: npm i next@latest
  3. Update aws-amplify and @aws-amplify/adapter-nextjs to latest (optional)
  4. Run npm run dev

Code Snippet

In middleware.ts:

import { type NextRequest, NextResponse } from "next/server";
import { authenticatedUser } from "./utils/amplify-server-utils";

export async function middleware(request: NextRequest) {
  const response = NextResponse.next();
  
  // Commenting out this line and all references to "user" makes the error go away
  const user = await authenticatedUser({ request, response });

  const isOnDashboard = request.nextUrl.pathname.startsWith("/dashboard");
  const isOnAdminArea =
    request.nextUrl.pathname.startsWith("/dashboard/admins");

  if (isOnDashboard) {
    if (!user)
      return NextResponse.redirect(new URL("/auth/login", request.nextUrl));
    if (isOnAdminArea && !user.isAdmin)
      return NextResponse.redirect(new URL("/dashboard", request.nextUrl));
    return response;
  } else if (user) {
    return NextResponse.redirect(new URL("/dashboard", request.nextUrl));
  }
}

export const config = {
  /*
   * Match all request paths except for the ones starting with
   */
  matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};

In amplify-server-utils

import { authConfig } from "@/app/amplify-cognito-config";
import { NextServer, createServerRunner } from "@aws-amplify/adapter-nextjs";
import { fetchAuthSession, getCurrentUser } from "aws-amplify/auth/server";

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

export async function authenticatedUser(context: NextServer.Context) {
  // runWithAmplifyServerContext seems to be the culprit
  return await runWithAmplifyServerContext({
    nextServerContext: context,
    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);
      }
    },
  });
}

Log output

// Put your logs below this line


aws-exports.js

Amplify.configure({
    Auth: {
        Cognito: {
            userPoolClientId: String(process.env.NEXT_PUBLIC_USER_CLIENT_ID),
            userPoolId: String(process.env.NEXT_PUBLIC_USER_POOL_ID),
            loginWith: {
                email: true,
            },
            userAttributes: {
                email: {
                    required: true
                },
                given_name: {
                    required: true
                },
                family_name: {
                    required: true
                },
            },
        }
    }
})

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

I found that downgrading NextJS version 15 makes this issue goes away, to something like version 14, but I would prefer to not do this.

@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 Feb 25, 2025
@HuiSF HuiSF added Core Related to core Amplify issues Next.js labels Feb 25, 2025
@HuiSF
Copy link
Member

HuiSF commented Feb 25, 2025

Hi @CarlWangMK thanks for reporting this issue. Looking at the screenshot shown error log and stack trace, it look like an internal function for parsing the Amplify configuration cannot terminate the recursive process.

Could you provide the authConfig object structure imported from @/app/amplify-cognito-config?

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Feb 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Core Related to core Amplify issues Next.js pending-triage Issue is pending triage
Projects
None yet
Development

No branches or pull requests

2 participants