amplify-js: RangeError: Maximum call stack size exceeded on NextJS v15 Middleware

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.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16 (9 by maintainers)

Most upvoted comments

Thank you for confirming it @silvioramalho! Glad the solution worked for you 🥳. Please feel free to let us know any time either in this thread or with new issue if you have face more issues or come up with any question.

Hey @CarlWangMK @AlexandreSantos76 @silvioramalho thank you for your patience. So what happened here is when you’re importing authConfig from amplify-cognito-config.ts, which is a Client Component, it also tried to run Amplify.configure() from server side. A NextJS Error message, Attempted to call authConfig() from the server but authConfig is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component. was supposed to surface, but the framework showed a different error here. Seems NextJS made a change to strictly enforce this behavior in v15 and that was what caused the problem.

For the workaround, please removeAmplify.configure() from Client Component and move authConfig to a Server Component. An example could be like

auth-config-export.tsx

import { type ResourcesConfig } from "aws-amplify";

export const authConfig: ResourcesConfig["Auth"] = {
  Cognito: {
    userPoolId: String(process.env.NEXT_PUBLIC_USER_POOL_ID),
    userPoolClientId: String(process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID),
  },
};

amplify-server-utils.ts

import { authConfig as authConfigTest } from "@/ui/config/auth-config-export";
import { NextServer, createServerRunner } from "@aws-amplify/adapter-nextjs";
import { fetchAuthSession, getCurrentUser } from "aws-amplify/auth/server";

export const { runWithAmplifyServerContext } = createServerRunner({
  config: {
    Auth: authConfigTest,
  },

...Rest of the code
});

One more suggestion is that rather than creating an Auth config, please consider using amplify_outputs.json like in

import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import outputs from '@/amplify_outputs.json';

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

You can find more of the examples in our documentation.

We’ll be happy to assist you further on this. Please let us know if the workaround works.

Hey @CarlWangMK @AlexandreSantos76 @silvioramalho thank you for your patience. So what happened here is when you’re importing authConfig from amplify-cognito-config.ts, which is a Client Component, it also tried to run Amplify.configure() from server side. A NextJS Error message, Attempted to call authConfig() from the server but authConfig is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component. was supposed to surface, but the framework showed a different error here. Seems NextJS made a change to strictly enforce this behavior in v15 and that was what caused the problem.

For the workaround, please removeAmplify.configure() from Client Component and move authConfig to a Server Component. An example could be like

auth-config-export.tsx

import { type ResourcesConfig } from “aws-amplify”;

export const authConfig: ResourcesConfig[“Auth”] = { Cognito: { userPoolId: String(process.env.NEXT_PUBLIC_USER_POOL_ID), userPoolClientId: String(process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID), }, }; amplify-server-utils.ts

import { authConfig as authConfigTest } from “@/ui/config/auth-config-export”; import { NextServer, createServerRunner } from “@aws-amplify/adapter-nextjs”; import { fetchAuthSession, getCurrentUser } from “aws-amplify/auth/server”;

export const { runWithAmplifyServerContext } = createServerRunner({ config: { Auth: authConfigTest, },

…Rest of the code }); One more suggestion is that rather than creating an Auth config, please consider using amplify_outputs.json like in

import { createServerRunner } from ‘@aws-amplify/adapter-nextjs’; import outputs from ‘@/amplify_outputs.json’;

export const { runWithAmplifyServerContext } = createServerRunner({ config: outputs }); You can find more of the examples in our documentation.

We’ll be happy to assist you further on this. Please let us know if the workaround works.

Hello @joon-won. Your solution worked fine for me. Good job!!! Thank you!!!

Thank you @silvioramalho, we’ll update you once we have a resolution to this issue.

I forked a repository with a working implementation and just updated some packages to a newer version so you can evaluate. The problem occurs even when I update aws-amplify to version 6.13.5 and @aws-amplify/adapter-nextjs to version 1.5.5.

Repo: https://github.com/silvioramalho/nextjs-cognito-auth/tree/upgrade-nextjs Branch: upgrade-nextjs

I hope this helps to evaluate. If you run the project you will see the problem happen.

In the original version (5-reset-password-end) the problem does not occur.

Hey @AlexandreSantos76, sorry to hear you’re experiencing issue with it. We’re currently looking into this issue, can you share your Amplify version and authConfig object structure imported from @/app/amplify-cognito-config as well?

Hey @CarlWangMK, we’re still investigating the issue. Thank you for your understanding and let us know any time if you have more questions.