Open didemkkaslan opened 1 month ago
Hi @didemkkaslan Thanks for opening this issue.
By looking at your sample code, you are implementing a ScopesContext
for your Client Components (as all the context APIs, such as createContext, useContext, and Provider, can only be used in Client Components in a Next.js app) along with the usage of the Amplify client-side fetchAuthSession()
API. If this is what you want to achieve, you only need to invoke Amplify.configure(config, { ssr: true })
(note the second parameter) on the client side.
In addition, the createKeyValueStorageFromCookieStorageAdapter
utility function is meant for use along with the generic Amplify SSR adapter exported from aws-amplify/adapter-core
, you should not need to use it in a Next.js app while @aws-amplify/adapter-nextjs
should be used.
Can you try to remove the useage of createKeyValueStorageFromCookieStorageAdapter
cognitoUserPoolsTokenProvider.setKeyValueStorage(keyValueStorage);
?
Hello @HuiSF sorry for the late reply. I had to use createKeyValueStorageFromCookieStorageAdapter
because we have a microsoft tab app implementation and there were issues related to authentication before implementing createKeyValueStorageFromCookieStorageAdapter
I had to include below code to make it work
const cookieOptions =
process.env.NEXT_PUBLIC_ENV === 'msteams'
? {
domain: 'tab.app.spiky.ai' as string,
sameSite: 'none' as 'lax' | 'strict' | 'none',
secure: true,
}
: {};
I'm a bit confused about if it is required to refetch scopes for token refresh events or should I only refetch the scopes when signIn or signInWithRedirect occurs
I've realised I haven't share the code I get the TooManyRequestsException error. So the problem is tokenRefresh event is fired many times so fetchAuthSession is called many times and we have the error
/* eslint-disable consistent-return */
/* eslint-disable default-case */
import { PeopleData } from '@/people/types/PeopleData';
import getPersonName from '@/people/utils/getPersonName';
import { getCurrentUser } from '@/settings/service/userService';
import { ONBOARDING_INTRODUCED_AT } from '@/shared/lib/getOnboardingStatus';
import { bootIntercom, shutdownIntercom } from '@/shared/lib/intercom';
import generateUserHash from '@/shared/services/generateUserHash';
import { useQueryClient } from '@tanstack/react-query';
import { fetchAuthSession } from 'aws-amplify/auth';
import { Hub } from 'aws-amplify/utils';
import dayjs from 'dayjs';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';
interface IdentificationProps {
children: React.ReactNode;
}
const sendUserDetailsToIntercom = async (user: PeopleData) => {
shutdownIntercom();
const userHash = await generateUserHash(user?.id);
const username = getPersonName(user);
bootIntercom({
app_id: process.env.NEXT_PUBLIC_INTERCOM_APP_ID,
name: username,
email: user?.email,
user_id: user?.id,
user_hash: userHash,
'Job Title': user?.title,
Company: user?.company?.companyName,
'Referral Source': user?.referralSource,
'Role Level': user?.roleLevel,
Department: user?.department,
'Company Size': user?.company?.companySize,
company: {
id: user?.company?.id,
name: user?.company?.companyName,
},
});
};
export default function Identification({ children }: IdentificationProps) {
const queryClient = useQueryClient();
const router = useRouter();
const hubListenerCancelToken = Hub.listen('auth', async ({ payload }) => {
if (payload.event !== 'signedOut') { // I get TOO MANY REQUESTS error here
const session = await fetchAuthSession();
queryClient.setQueryData(
['scopes'],
session?.tokens?.idToken?.payload?.scope?.split(' ') ?? [],
);
}
switch (payload.event) {
case 'signInWithRedirect': {
console.log('signInWithRedirect');
break;
}
case 'signedIn': {
console.log('signedIn');
const user = await getCurrentUser();
sendUserDetailsToIntercom(user);
// Check whether the user has completed the onboarding
const onboardingCompleted = user?.onboardingCompleted === true;
const isAfterOnboardingIntroducedAt = dayjs(user?.createdAt).isAfter(
ONBOARDING_INTRODUCED_AT,
);
const isRedirectToOnboarding =
!onboardingCompleted && isAfterOnboardingIntroducedAt;
if (isRedirectToOnboarding) {
router.push('/onboarding/personal-info');
} else {
router.push('/meetings');
}
break;
}
case 'signedOut': {
// Here we need to shutdown Intercom and boot it again to clear the user data when the user signs out
shutdownIntercom();
bootIntercom();
break;
}
}
});
useEffect(() => {
if (typeof window === 'undefined' || !window.Intercom) return;
return () => {
hubListenerCancelToken();
};
}, []);
return children;
}
@didemkkaslan I had to de-deuplicate fetchAuthSession so only a single instance of it can fire at once. See #13499.
Before opening, please confirm:
JavaScript Framework
Next.js
Amplify APIs
REST API
Amplify Version
v6
Amplify Categories
api
Backend
CDK
Environment information
Describe the bug
Hello, I'm using
fetchAuthSession
to get idtoken and use it as Authorization header. And also I use it to get user scopes I started to get TooManyRequestsException is there anything I should shouldn't do? Not sure how to approach this problem. Thanks in advanceExpected behavior
No rate limit errors
Reproduction steps
Use fetchAuthSession multiple places in the app
Code Snippet
Log output
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