amplify-js: Next, js, Amplify js.fetchAuthSession({forceRefresh: true}) does not work as expected and returns tokens as undefined. How to manage a refresh token in Amplify v6 in Next.js
Before opening, please confirm:
- I have searched for duplicate or closed issues and discussions.
- I have read the guide for submitting bug reports.
- I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
JavaScript Framework
Next.js
Amplify APIs
Authentication
Amplify Version
v6
Amplify Categories
auth
Backend
None
Environment information
# Put output below this line
Describe the bug
Hello and thanks for the great library. I have the following problem. I need a token to set in the headers of each request as Authorization: Bearer ${token}. I am currently taking the accessToken from the fetchAuthSession and setting it in the headers. For this purpose I use axios interceptor. The problem is that if some time passes, about 15 minutes, and the application is not used, the token expires.
Accordingly, you will see that if I do not have a token, the authorization header is not submitted, which is a problem for me. The app only fixes after a refresh, but I want to get the refresh token without forcing the user to refresh because they might lose data.
Expected behavior
Is there a way Amplify to handle the refresh token itself, or to force refresh it when It expires ? I always need a valid token for my Authorization headers.
Reproduction steps
…
Code Snippet
// Put your code below this line.
// _app.tsx
import { type AppType } from "next/dist/shared/lib/utils";
import {
QueryClient,
QueryClientProvider,
} from 'react-query'
import NextTopLoader from 'nextjs-toploader';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Amplify } from "aws-amplify";
import '@aws-amplify/ui-react/styles.css';
import AuthWrapper from "~/components/auth/AuthWrapper";
import "~/styles/globals.css";
import { DataProvider } from '~/context/globalState';
import { PdfFocusProvider } from "~/context/pdf";
import { CadDataProvider } from "~/context/cadData";
Amplify.configure({
Auth: {
Cognito: {
userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID ?? "",
userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID ?? "",
loginWith: {
oauth: {
domain: process.env.OAUTH_DOMAIN ?? "",
scopes: ['email'],
redirectSignIn: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_IN ?? ""],
redirectSignOut: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_OUT ?? ""],
// I tried to change responseType to "code", but it is not working for me
responseType: 'token',
},
username: false,
email: true,
phone: false,
}
}
}
});
const MyApp: AppType = ({ Component, pageProps }) => {
const queryClient = new QueryClient();
return (
<AuthWrapper>
<QueryClientProvider client={queryClient}>
<DataProvider>
<PdfFocusProvider>
<CadDataProvider>
<ToastContainer autoClose={1000} />
<NextTopLoader color="#120264" showSpinner height={3} />
<Component {...pageProps} />
</CadDataProvider>
</PdfFocusProvider>
</DataProvider>
</QueryClientProvider>
</AuthWrapper>
);
};
export default MyApp;
// apiClient.ts
import axios from "axios";
import { fetchAuthSession } from "aws-amplify/auth";
import { backendUrl } from "~/config";
const apiClient = axios.create({
baseURL: backendUrl,
responseType: "json",
});
apiClient.interceptors.request.use(
async (config) => {
try {
// When we get to this block tokens is always different from undefined, even if I pass {forceRefresh: true}
const session = await fetchAuthSession();
const accessToken = session.tokens?.accessToken?.toString();
if (accessToken) {
// here token is always different from undefined.
config.headers.Authorization = `Bearer ${accessToken}`;
console.log("Access Token set in request:", accessToken);
} else {
console.warn("No access token available");
}
} catch (error) {
console.error("Error fetching auth token", error);
}
return config;
},
(error) => Promise.reject(error)
);
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error?.response?.status === 401 && !originalRequest._retry) {
console.log("401 Unauthorized error, trying to refresh token");
// I am getting into this block when token expires
try {
const session = await fetchAuthSession({ forceRefresh: true });
// but here the tokens object is always undefined
const refreshToken = session.tokens?.accessToken?.toString();
if (refreshToken) {
console.log("Refresh token obtained:", refreshToken);
originalRequest.headers.Authorization = `Bearer ${refreshToken}`;
originalRequest._retry = true;
return apiClient(originalRequest);
} else {
console.warn("No refresh token available");
}
} catch (authError) {
console.error("Error refreshing auth token", authError);
return Promise.reject(authError);
}
}
return Promise.reject(error);
}
);
export default apiClient;
Log output
// Put your logs below this line
aws-exports.js
/* eslint-disable */ // WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.
const awsmobile = { “aws_project_region”: “us-east-2” };
export default awsmobile;
Manual configuration
Amplify.configure({ Auth: { Cognito: { userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID ?? “”, userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID ?? “”, loginWith: { oauth: { domain: process.env.OAUTH_DOMAIN ?? “”, scopes: [‘email’], redirectSignIn: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_IN ?? “”], redirectSignOut: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_OUT ?? “”], responseType: ‘token’, }, username: false, email: true, phone: false, } } } });
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 2 years ago
- Reactions: 1
- Comments: 16 (8 by maintainers)
yes I understand, the problem is the same. We are reproducing the problem - the application is open without interaction in the browser for about 15 minutes. That is, no requests are executed within 15 minutes. Then I get a network error where the request returns a 401 because I don’t have the authorization header set. I think I go in here refreshedToken is undefined and that’s why I don’t have any headers set:
The interesting thing is that initial fetchAuthSession works and returns tokens, but in this case, which I am describing to you, it does not return them to me. Here are some screenshot of errors while I have responseType set to code.
this is my apiClient.ts
And this is the Amplify config object: