I'm trying to use CognitoIdentityProviderClient
server side in my next.js application that also uses amplify js library and amplify hosting. It works perfectly locally, but the client is not authenticated and authorized after deploy.
import type { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth/next';
import errorString from '@/utils/errorString';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
// import { defaultProvider } from '@aws-sdk/credential-provider-node';
import {
AdminGetUserCommand,
CognitoIdentityProviderClient,
} from '@aws-sdk/client-cognito-identity-provider';
import { updatedAwsConfig } from '@/utils/amplify-init';
const handler = async (
req: NextApiRequest,
res: NextApiResponse
) => {
try {
const session = await getServerSession(req, res, authOptions)
const { user } = session || {};
const region = updatedAwsConfig.aws_cognito_region;
const adminGetUser = async ({ userPoolId, username }) => {
const client = new CognitoIdentityProviderClient({ region,
// credentials: defaultProvider()
});
const command = new AdminGetUserCommand({
UserPoolId: userPoolId,
Username: username,
});
return client.send(command);
};
const userPoolId = updatedAwsConfig.aws_user_pools_id;
const username = user.username;
const data = await adminGetUser({userPoolId, username});
return res.status(200).json({ data });
} catch(error) {
return res.status(500).json({ error: errorString(error) });
}
};
export default handler;
It probably uses some credentials like ~/.aws/credentials locally and doesn't have them server side. I also tried defaultProvider from @aws-sdk/credential-provider-node without success. I also assigned the same IAM roles for the backend role as I have for my local amplify without success. Are there ideas how could I make CognitoIdentityProviderClient work properly?
I need server side credentials for the admin api. Users don't have amplify sessions.