Cognito Authentication in Node.js with AWS-SDK and Typescript
In this article, I will show how you create UserPool in Cognito as well as how to create a user in UserPool, user login, access token…
Cognito Authentication in Node.js with AWS-SDK and Typescript
In this article, I will show how you create UserPool in Cognito as well as how to create a user in UserPool, user login, access token validation, create groups, and add user in group in Cognito UserPool. GitHub link — https://github.com/RohitChanda/Cognito_with_Node

With Amazon Cognito, you can add user sign-up and sign-in features and control access to your web and mobile applications. Amazon Cognito supports various compliance regulations and integrates with frontend and backend development resources.
Developers can use Cognito Identity to add sign-up and sign-in to their apps and to enable their users to securely access their app’s resources. Cognito also enables developers to sync data across devices, platforms, and applications.
A User pool is a user directory in Amazon Cognito. With a user pool, your users can sign in to your web or mobile app through Amazon Cognito.
User pool provides:
- Sign-up and sign-in services.
- A built-in, customizable web UI to sign in users.
- Social sign-in with Facebook, Google, Login with Amazon, and Sign in with Apple, as well as sign-in with SAML identity providers from your user pool.
- User directory management and user profiles.
- Security features such as multi-factor authentication (MFA), checks for compromised credentials, account takeover protection, and phone and email verification.
- Customized workflows and user migration through AWS Lambda triggers.
Create Cognito User Pool
-
Open the AWS Official site and sign in to your console.
-
After Signing in to your console, search Cognito and click it.

- Click to manage User Pools.

- Click Create user pool button


- Write down the pool name and create it by clicking the Step through settings button, or you can choose default settings by clicking the Review defaults button.



Also, you can add custom attributes in Cognito.


Create App Client. Remember one thing uncheck the Generate client secret option.


Create a user in Cognito UserPool
- First set up AWS-SDK in your backend repository.
import AWS from 'aws-sdk'
import dotenv from 'dotenv'
dotenv.config()
AWS.config.update({
region: process.env.AWS_REGION,
accessKeyId: process.env.ACCESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY
})
export default AWS
- set up Cognito
import AWS from "../config/aws-sdk"
import * as dotenv from "dotenv"
import { CognitoSignupPayload, AddUserINGroupPayload } from "../interface/auth"
import axios from "axios"
import JWT from 'jsonwebtoken'
import jwkToPem from 'jwk-to-pem'
dotenv.config()
const poolData:{UserPoolId:string, ClientId:string, PoolRegion:string } = {
UserPoolId : process.env.AWS_COGNITO_USER_POOL_ID as string,
ClientId : process.env.AWS_COGNITO_CLIENT_ID as string,
PoolRegion : process.env.AWS_REGION as string
}
const cognito = new AWS.CognitoIdentityServiceProvider({region: poolData.PoolRegion})
- User SignUp function
export function SignUp(body:CognitoSignupPayload){
const { email ,firstName, lastName, designation} = body
return new Promise((resolve, reject)=>{
cognito.adminCreateUser({
UserPoolId: poolData.UserPoolId,
Username: email,
DesiredDeliveryMediums: ['EMAIL'],
//MessageAction: 'SUPPRESS', //stop sending the invitation
//MessageAction: 'RESET', // resend the invitation message to a user that already exists
TemporaryPassword: "temp#1234", // If you don't specify a value, Amazon Cognito generates one for you.
UserAttributes: [
{
Name : 'email',
Value : email
},
{
Name : 'given_name',
Value : firstName
},
{
Name : 'family_name',
Value : lastName
},
{
Name : 'custom:designation', // custome attribute
Value : designation
},
]
},function(err,response){
if(err){
reject(new Error(err.message))
}else{
resolve(response.User)
}
})
})
}
in controller function
import { Request, Response} from 'express'
import { CognitoSignupPayload} from '../interface/auth'
import {SignUp } from '../cognito/cognito'
export async function addUserInCognito(req:Request,res:Response) {
try {
const { email, first_name, last_name, designation } = req.body
const payload: CognitoSignupPayload = {
email : email,
firstName : first_name,
lastName : last_name,
designation : designation
}
const result = await SignUp(payload)
res.status(200).json({
response: result,
message: "User added in cognito"
})
} catch (error) {
console.log(error);
res.status(500).json({
message: "something went wrong!"
});
}
}
- User login
export function UserLogin(payload:{email:string,password:string}){
const { email, password } = payload
return new Promise((resolve, reject)=>{
cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId: poolData.ClientId,
UserPoolId: poolData.UserPoolId,
AuthParameters: {
USERNAME: email,
PASSWORD: password
}
},function(err,response){
if(err){
reject(err)
return
}
resolve(response)
})
})
}
in controller
export async function userLogin(req:Request,res:Response) {
try {
const { email, password } = req.body
const payload = {
email:email,
password:password
}
const result:any = await UserLogin(payload)
if( result.ChallengeName == 'NEW_PASSWORD_REQUIRED' ) {
res.status(200).json({
ChallengeName:result.ChallengeName,
session: result.Session,
message: "SET NEW PASSWORD"
})
}
res.status(200).json({
response: result,
message: "User logged in successfully"
})
} catch (error:any) {
res.status(500).json({
message: error.message
});
}
}
If a user logged in for the first time then the response object will be like
{
"ChallengeName": "NEW_PASSWORD_REQUIRED",
"session": "string",
"message": "SET NEW PASSWORD"
}
It means now the user has to set a new password. for this functionality, we have to use the adminRespondToAuthChallenge method from Cognito.
export async function newPasswordRequired(payload:{email:string, newPassword:string, session:string}){
const { email, newPassword, session } = payload
return new Promise((resolve, reject)=>{
cognito.adminRespondToAuthChallenge({
ChallengeName: 'NEW_PASSWORD_REQUIRED',
ClientId: poolData.ClientId,
UserPoolId: poolData.UserPoolId,
ChallengeResponses: {
USERNAME: email,
NEW_PASSWORD: newPassword,
},
Session: session
},function(err,response){
if(err){
reject(err)
}else{
resolve(response)
}
})
})
}
response object
"response": {
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "string",
"ExpiresIn": number
"TokenType": "string"
"RefreshToken": "string",
"IdToken": "string",
}
},
next time, when the user tries to log in, Cognito API will return a response object like this
"response": {
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "string"
"TokenType": "Bearer",
"RefreshToken": "string"
"IdToken": "string"
}
},
- Validate access token
import AWS from "../config/aws-sdk"
import * as dotenv from "dotenv"
import axios from "axios"
import JWT from 'jsonwebtoken'
import jwkToPem from 'jwk-to-pem'
dotenv.config()
export function validateAccessToken(token:string) {
return new Promise((resolve, reject) => {
axios.get(`https://cognito-idp.${poolData.PoolRegion}.amazonaws.com/${poolData.UserPoolId}/.well-known/jwks.json`, {headers: {'Content-Type': 'application/json'}})
.then((response)=>{
const body = response.data;
const pem = jwkToPem(body.keys[1])
JWT.verify(token, pem, function(err:any, payload:any) {
if(err) {
reject(new Error('Invalid token'))
} else {
resolve(payload)
}
})
})
.catch((err)=>{
console.log(err);
reject(err)
})
})
}
- Create Group in Cognito
export function createGroup(groupName:string){
return new Promise((resolve, reject)=>{
cognito.createGroup({
GroupName: groupName,
UserPoolId: poolData.UserPoolId
},function(err,response){
if(err){
reject(err)
}else{
resolve(response)
}
})
})
}
- Add user to Group
export function addUserIntoGroup( payload:AddUserINGroupPayload ){
const {groupName, userName} = payload
return new Promise((resolve, reject)=>{
cognito.adminAddUserToGroup({
GroupName: groupName,
Username: userName,
UserPoolId: poolData.UserPoolId
},function(err,response){
if(err){
reject(err)
}else{
resolve(response)
}
})
})
}
For more info about Cognito API, you can check **AWS Cognito Documentation.**
메타데이터
- post_id
- dcf031d54e8f
- slug
- cognito-authentication-in-node-js-with-aws-sdk-and-typescript-dcf031d54e8f
- url
- https://medium.com/@rohit.chanda.93/cognito-authentication-in-node-js-with-aws-sdk-and-typescript-dcf031d54e8f
- canonical_url
- https://medium.com/@rohit.chanda.93/cognito-authentication-in-node-js-with-aws-sdk-and-typescript-dcf031d54e8f
- author_url
- https://medium.com/@rohit.chanda.93
- status
- ok
- fetched_at
- 2026-07-28 22:35:20