Skip to content

Instantly share code, notes, and snippets.

@sjmach
Forked from JeremyPlease/signed-cloudfront-url.js
Created January 18, 2021 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjmach/0c1572aab5d682ce490c96462190e54a to your computer and use it in GitHub Desktop.
Save sjmach/0c1572aab5d682ce490c96462190e54a to your computer and use it in GitHub Desktop.
// load the AWS SDK
const AWS = require('aws-sdk')
// load CloudFront key pair from environment variables
// Important: when storing your CloudFront private key as an environment variable string,
// you'll need to replace all line breaks with \n, like this:
// CF_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIE...1Ar\nwLW...2eL\nFOu...k2E\n-----END RSA PRIVATE KEY-----"
const cloudfrontAccessKeyId = process.env.CF_ACCESS_KEY_ID
const cloudFrontPrivateKey = process.env.CF_PRIVATE_KEY
const signer = new AWS.CloudFront.Signer(cloudfrontAccessKeyId, cloudFrontPrivateKey)
// 2 days as milliseconds to use for link expiration
const twoDays = 2*24*60*60*1000
// sign a CloudFront URL that expires 2 days from now
const signedUrl = signer.getSignedUrl({
url: 'https://248hf0w8hs.cloudfront.net/secret-image.jpg',
expires: Math.floor((Date.now() + twoDays)/1000), // Unix UTC timestamp for now + 2 days
})
// signedUrl is now a signed CloudFront URL:
// https://248hf0w8hs.cloudfront.net/secret-image.jpg?Expires=1531165045&Key-Pair-Id=HDIWEUY39S87XHCJDJUQODJ20AL&Signature=0SGI2...K2JHID__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment