Skip to content

Authentication Redirect Loop with Amplify Cognito in Next.js (Next 15.4.1, Amplify 5.3.26) #14203

Closed as not planned
@rushicruk

Description

@rushicruk

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

GraphQL API

Amplify Version

v5

Amplify Categories

auth

Backend

None

Environment information

# Put output below this line


Describe the bug

I'm using SSO signin for our admin console authentication. After successful authentication via Cognito, the user is unexpectedly redirected back to the sign-in page. This occurs despite receiving a valid authorisation code and no explicit errors in the console. I'm currently migrating CRA to Nextjs. Same code works in React.

Additional Context:

  • The Auth.currentAuthenticatedUser() call in getUser() appears to fail silently after the redirect.
  • No errors in browser console/network tab during the flow.
  • Cognito app client settings include correct callback URLs.
  • Issue occurs in local/PR development environments.
  • Token storage mechanism (localStorage vs cookies) may be relevant due to SSR.

Troubleshooting Attempted:

  • Verified Cognito domain/app client configuration.

Expected behavior

After successful authentication, the user should remain authenticated and not be redirected to the sign-in page and navigate me to respective page.

Reproduction steps

nA

Code Snippet

"use client";
import { useCallback, useEffect, useState } from "react";
import { Auth } from "aws-amplify";
import { CognitoUser } from "amazon-cognito-identity-js";

export const useAuth = () => {
  const [user, setUser] = useState<CognitoUser>();
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isAuthorized, setIsAuthorized] = useState(false);

  const getUser = useCallback(async () => {
    if (process.env.NEXT_PUBLIC_DISABLE_AUTH === "true") {
      setIsAuthenticated(true);
      setIsAuthorized(true);
    } else {
      try {
        const authUser: CognitoUser =
          (await Auth.currentAuthenticatedUser()) as CognitoUser;
        if (authUser) {
          setUser(authUser);
          setIsAuthenticated(true);
          setIsAuthorized(
            !!(
              authUser.getSignInUserSession()?.getAccessToken().payload[
                "cognito:groups"
              ] as string[]
            )?.includes("admin_groups")
          );
        } else {
          setIsAuthenticated(false);
        }
      } catch (e) {
        setIsAuthenticated(false);
      }
    }
    setIsLoading(false);
  }, []);

  useEffect((): void => {
    getUser();
  }, [getUser]);

  const login =
    process.env.NEXT_PUBLIC_DISABLE_AUTH === "true"
      ? () => Promise.resolve()
      : () => Auth.federatedSignIn();

  return {
    user: user?.getSignInUserSession(),
    isAuthenticated,
    isAuthorized,
    logout: () => Auth.signOut(),
    login,
    isLoading,
  };
};

export default useAuth;

Log output

// Put your logs below this line


aws-exports.js

No response

Manual configuration

{
      aws_project_region: process.env.NEXT_PUBLIC_REGION,
      aws_user_pools_id: config.userPoolId,
      aws_user_pools_web_client_id: config.userPoolClientId,
      oauth: {
        domain: config.userPoolDomain,
        redirectSignIn: `${config.url}/admin`,
        redirectSignOut: config.url,
        responseType: "code",
      },
      API: {
        aws_appsync_graphqlEndpoint: config.apiGraphQlEndpoint,
        aws_appsync_region: process.env.NEXT_PUBLIC_REGION,
        aws_appsync_authenticationType: "API_KEY",
        aws_appsync_apiKey: config.publicApiKey,
      },
      ssr: true,
}

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Next.jsSSRIssues related to Server Side RenderingV5questionGeneral question

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions