amplify-js: NextJS + Amplify V6 signIn command returns `User needs to be authenticated to call this API` even when its runned in client side with SSR enabled

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

No response

Backend

Amplify CLI

Environment information

  System:
    OS: macOS 14.2.1
    CPU: (8) arm64 Apple M1
    Memory: 698.50 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.10.0 - /usr/local/bin/node
    npm: 10.2.3 - /usr/local/bin/npm
  Browsers:
    Chrome: 120.0.6099.234
    Edge: 120.0.2210.144
    Safari: 17.2.1
  npmPackages:
    @ampproject/toolbox-optimizer:  undefined ()
    @aws-amplify/adapter-nextjs: ^1.0.9 => 1.0.9 
    @aws-amplify/adapter-nextjs/api:  undefined ()
    @aws-amplify/adapter-nextjs/data:  undefined ()
    @aws-amplify/ui-react: ^6.0.7 => 6.0.7 
    @aws-amplify/ui-react-internal:  undefined ()
    @babel/core:  undefined ()
    @babel/runtime:  7.22.5 
    @edge-runtime/cookies:  4.0.2 
    @edge-runtime/ponyfill:  2.4.1 
    @edge-runtime/primitives:  4.0.2 
    @formatjs/intl-localematcher: ^0.5.2 => 0.5.2 
    @hapi/accept:  undefined ()
    @mswjs/interceptors:  undefined ()
    @napi-rs/triples:  undefined ()
    @next/font:  undefined ()
    @next/react-dev-overlay:  undefined ()
    @opentelemetry/api:  undefined ()
    @radix-ui/react-alert-dialog: ^1.0.5 => 1.0.5 
    @radix-ui/react-icons: ^1.3.0 => 1.3.0 
    @radix-ui/react-label: ^2.0.2 => 2.0.2 
    @radix-ui/react-navigation-menu: ^1.1.4 => 1.1.4 
    @radix-ui/react-slot: ^1.0.2 => 1.0.2 (1.0.0)
    @segment/ajv-human-errors:  undefined ()
    @types/negotiator: ^0.6.3 => 0.6.3 
    @types/node: ^20 => 20.9.1 
    @types/react: ^18 => 18.2.37 
    @types/react-dom: ^18 => 18.2.15 
    @vercel/nft:  undefined ()
    @vercel/og:  0.5.15 
    acorn:  undefined ()
    amphtml-validator:  undefined ()
    anser:  undefined ()
    arg:  undefined ()
    assert:  undefined ()
    async-retry:  undefined ()
    async-sema:  undefined ()
    autoprefixer: ^10.0.1 => 10.4.16 
    aws-amplify: ^6.0.9 => 6.0.9 
    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/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.0.0 => 2.0.0 
    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.53.0 
    eslint-config-next: 14.0.3 => 14.0.3 
    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 ()
    micromatch:  undefined ()
    mini-css-extract-plugin:  undefined ()
    nanoid:  undefined ()
    native-url:  undefined ()
    negotiator: ^0.6.3 => 0.6.3 
    neo-async:  undefined ()
    next: 14.0.3 => 14.0.3 
    next-auth: ^4.24.5 => 4.24.5 
    node-fetch:  undefined ()
    node-html-parser:  undefined ()
    ora:  undefined ()
    os-browserify:  undefined ()
    p-limit:  undefined ()
    path-browserify:  undefined ()
    platform:  undefined ()
    postcss: ^8 => 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 (16.14.0)
    react-builtin:  undefined ()
    react-code-input: ^3.10.1 => 3.10.1 
    react-dom: ^18 => 18.2.0 (16.14.0)
    react-dom-builtin:  undefined ()
    react-dom-experimental-builtin:  undefined ()
    react-experimental-builtin:  undefined ()
    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 ()
    shell-quote:  undefined ()
    source-map:  undefined ()
    stacktrace-parser:  undefined ()
    stream-browserify:  undefined ()
    stream-http:  undefined ()
    string-hash:  undefined ()
    string_decoder:  undefined ()
    strip-ansi:  undefined ()
    superstruct:  undefined ()
    tailwind-merge: ^2.1.0 => 2.1.0 
    tailwindcss: ^3.3.0 => 3.3.5 
    tailwindcss-animate: ^1.0.7 => 1.0.7 
    tar:  undefined ()
    terser:  undefined ()
    text-table:  undefined ()
    timers-browserify:  undefined ()
    tty-browserify:  undefined ()
    typescript: ^5 => 5.2.2 
    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 ()
  npmGlobalPackages:
    @aws-amplify/cli: 10.7.1
    corepack: 0.22.0
    eas-cli: 3.4.1
    expo-cli: 6.1.0
    npm: 10.2.3


Describe the bug

When I run the signIn command imported from import { signIn, type SignInInput } from "aws-amplify/auth"; in a file marked with use client it returns te following error: User needs to be authenticated to call this API. Ive also enables SSR inside Amplify.configure. I really can’t figure out how to fix this problem for days now. Ive followed every step in the official docs. Thanks in advance.

Expected behavior

The command needs to sign me in.

Reproduction steps

  1. Running from a <form onSubmit={handleSignin} > the command signIn({ username, password })
  2. It returns: User needs to be authenticated to call this API even when its runned with “use client”

Code Snippet

Login.tsx:


"use client";

import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "../button";
import { ExclamationTriangleIcon, ReloadIcon } from "@radix-ui/react-icons";
import { FormEvent, useState } from "react";
import { Alert, AlertDescription } from "../alert";
import handleSignIn from "@/hooks/useSignIn";

export default function LoginModal(lang: any) {
    const [loading, setLoading] = useState<boolean>(false);
    const [email, setEmail] = useState<string>("");
    const [password, setPassword] = useState<string>("");
    const [signinResponse, setSigninResponse] = useState<any[]>([false, 0, ""]);

    const onSignIn = async (e: any) => {
        e.preventDefault();
        setLoading(true);
        setSigninResponse([false, 0, ""]);
        try {
            const response = await handleSignIn({
                username: email,
                password: password,
            });
            if (response[0]) {
                console.log(response);
            } else {
                setSigninResponse([true, 0, response[2]]);
            }
        } catch (error: any) {
            console.error("Fout bij inloggen:", error);
            setSigninResponse([true, 0, error.message]);
        } finally {
            setLoading(false);
        }
    };

    return (
        <AlertDialog>
            <AlertDialogTrigger className="hover:bg-accent hover:text-primary text-sm">
                Inloggen
            </AlertDialogTrigger>
            <AlertDialogContent className="bg-white">
                <AlertDialogHeader className="border-b pb-3">
                    <AlertDialogTitle className="text-xl">
                        Welkom terug!
                    </AlertDialogTitle>
                </AlertDialogHeader>
                <form className="w-full h-full grid gap-2" onSubmit={onSignIn}>
                    <div className="grid w-full max-w-sm items-center gap-1.5">
                        <Label htmlFor="email">Emailadres</Label>
                        <Input
                            type="email"
                            id="email"
                            className={
                                signinResponse[1] === 1 ? "!border-alert" : ""
                            }
                            onChange={(e: FormEvent<HTMLInputElement>) =>
                                setEmail(e.currentTarget.value)
                            }
                        />
                    </div>
                    <div className="grid w-full max-w-sm items-center gap-1.5">
                        <Label htmlFor="password">Wachtwoord</Label>
                        <Input
                            type="password"
                            id="password"
                            className={
                                signinResponse[1] === 2 ? "!border-alert" : ""
                            }
                            onChange={(e: FormEvent<HTMLInputElement>) =>
                                setPassword(e.currentTarget.value)
                            }
                        />
                    </div>
                    <AlertDialogFooter className="flex flex-col">
                        {signinResponse[2] !== "" && (
                            <Alert variant="destructive" className="mb-2">
                                <ExclamationTriangleIcon className="h-4 w-4" />
                                <AlertDescription className="pt-1">
                                    {signinResponse[2]}
                                </AlertDescription>
                            </Alert>
                        )}
                        <span className="text-sm text-primary hover:text-secondary hover:cursor-pointer">
                            Wachtwoord vergeten?
                        </span>
                        <span className="text-sm mt-2 text-primary hover:text-secondary hover:cursor-pointer">
                            Geen account?
                        </span>
                    </AlertDialogFooter>
                    {loading ? (
                        <Button disabled>
                            <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
                            Inloggen
                        </Button>
                    ) : (
                        <Button variant={"default"} type="submit">
                            Inloggen
                        </Button>
                    )}
                </form>
                <AlertDialogCancel className="text-xs hover:underline cursor-pointer">
                    Annuleren
                </AlertDialogCancel>
            </AlertDialogContent>
        </AlertDialog>
    );
}


useSignIn.ts:


"use client";
import { signIn, type SignInInput } from "aws-amplify/auth";

export default async function handleSignIn({
    username,
    password,
}: SignInInput) {
    try {
        const { isSignedIn, nextStep } = await signIn({ username, password });
        console.log(isSignedIn, nextStep);
        return [true, 0, ""];
    } catch (error: any) {
        return [false, 0, error.message.toString()];
    }
}

layout.tsx:


import type { Metadata } from "next";
import { Poppins } from "next/font/google";
import "./globals.css";
import { site } from "@/configuration";
import TopNavigation from "@/components/nav/site/topnav";
import clsx from "clsx";
import { getDictionary } from "@/hooks/useDictionaries";
import RootLayoutThatConfiguresAmplifyOnTheClient from "@/utils/amplifyConfigureOnClient";

type LayoutProps = {
    params: { lang: string };
    children: React.ReactNode;
};

const font = Poppins({
    variable: "--font-poppins",
    weight: "400",
    subsets: ["latin"],
});

export const metadata: Metadata = {
    title: site.name,
    description: site.description,
};

export default async function RootLayout({ children, params }: LayoutProps) {
    const dict = await getDictionary(params.lang);

    return (
        <html lang={params.lang}>
            <RootLayoutThatConfiguresAmplifyOnTheClient>
                <body
                    className={clsx(
                        font.className,
                        "h-screen w-screen overflow-hidden"
                    )}
                >
                    <TopNavigation lang={dict} />
                    <div className="h-full overflow-auto mx-auto max-w-screen">
                        {`Locale: ${params.lang}`}
                        {children}
                    </div>
                </body>
            </RootLayoutThatConfiguresAmplifyOnTheClient>
        </html>
    );
}

amplifyConfigureOnClient.ts:


"use client";

import config from "@/amplifyconfiguration.json";
import { Amplify } from "aws-amplify";

Amplify.configure(config, {
    ssr: true,
});

export default function RootLayoutThatConfiguresAmplifyOnTheClient({
    children,
}: {
    children: React.ReactNode;
}) {
    return children;
}


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

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (9 by maintainers)

Most upvoted comments

hello @muratcali . Sorry to hear you are experiencing issues with the library. We will reproduce this issue and will follow up with any updates

Hey guys my bad 😅. I just find out that this line: cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage)

Was the cause of the issue for me, I saw it here in the docs so I never thought that line will be causing issues in my app lol. Let me know if that’s an expected behavior. But I believe it’s not.

Now everything works great!