Im currently working in a Next.js frontend and NestJS backend application and im setting the login component with the @aws-amplify/ui-react:
like in the documentation
https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/#option-1-use-pre-built-ui-components
import { Amplify } from 'aws-amplify';
import { withAuthenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
function App({ signOut, user }) {
return (
<>
<h1>Hello {user.username}</h1>
<button onClick={signOut}>Sign out</button>
</>
);
}
export default withAuthenticator(App);
The problem is how can i get the jwt token and pass it to axios header?
const response: any = await axios({
method: method as Method,
url: `http://localhost:3001/dev/${query}`,
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
},
data,
})
i`ve try to get the token from local storage but the key aways change because of the pool id and the user.
2
Answers
Look at the Example PAM app. It uses a React app and uses Cognito to autheniate users. This app does not use amplify. It uses React, Cloudscape Design System, and the AWS SDK and makes requests to API Gateway endpoints:
As you can see in this illustration, the React app lets a user log in via a Cognito call. This app uses a token returned from Cognito. Once you understand that – you can apply it to your projects.
After you follow the instructions in this example, you get the full app which includes a login screen:
Once you log in – you see the app:
Look at the code in this example:
React code is here:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/clients/react/elros-pam
Backend example is here:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files
Don’t know exact syntax about Next.js, but this is how I did in Angular (TypeScript).
ProfileComponent.ts
UserService.ts