Skip to content

Instantly share code, notes, and snippets.

@mitchwongho
Last active July 7, 2025 18:12
Show Gist options
  • Save mitchwongho/29a09691c637a10e66ef38832aa66256 to your computer and use it in GitHub Desktop.
Save mitchwongho/29a09691c637a10e66ef38832aa66256 to your computer and use it in GitHub Desktop.
Generate a signed URL using AWS Signature Version 4 (SigV4) for ElastiCache IAM authentication.
import * as aws4 from 'aws4';
type Credentials = {
accessKeyId: string,
secretAccessKey: string,
sessionToken: string
};
/**
* Generate a signed request to the AWS ElastiCache service for IAM authentication
*/
const getToken = (
credentials: Credentials,
userId: string,
cacheName: string,
region: string = 'eu-west-1',
isServerless: boolean = true,
expiry: number = 900 // seconds
): string => {
const signed = aws4.sign(
{
service: 'elasticache',
region,
method: 'GET',
host: cacheName,
setHost: true,
path: `/?Action=connect&User=${encodeURI(userId)}${
isServerless ? '&ResourceType=ServerlessCache' : ''
}&X-Amz-Expires=${expiry}`,
protocol: 'http',
signQuery: true,
body: ''
},
{
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken
}
);
return `${signed.host}${signed.path}`.replace('http://', '');
};
// usage:
// getToken();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment