GithubHelp home page GithubHelp logo

gekorm / aws-sih Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 1.0 8.68 MB

AWS solution to dynamically edit images on the fly with SharpJS

License: Apache License 2.0

Shell 0.69% TypeScript 95.04% JavaScript 1.33% HTML 2.75% CSS 0.19%
aws-cdk image-compression image-processing lambda optimize-images responsive-images sharp

aws-sih's Introduction

Fork of Serverless Image Handler

Table of Contents

Changes in this fork

  • New URL scheme. Edit with Sharp using search (query) parameters for better SEO. See Usage
  • Custom domain. A certificate and hosted zone is automatically generated for your domain
  • Improved cache hit ratio when AutoWebPParameter is enabled
  • Origin Shield support for improved cache hit ratio and performance
  • Disabled data collection
  • Upgraded dependencies
  • Scripts are only run from local dependencies (uses npm run instead of npx) for greater reliability

Deploying or Customizing the Solution

Prerequisites

1. Clone the repository

git clone https://github.com/GeKorm/aws-sih.git
cd aws-sih
export MAIN_DIRECTORY=$PWD

2. Unit Test

After making changes, run unit tests to make sure added customization passes the tests:

cd $MAIN_DIRECTORY/deployment
chmod +x run-unit-tests.sh && ./run-unit-tests.sh

3. Build and Deploy

Pick either

Default generated cloudfront domain

cd $MAIN_DIRECTORY/source/constructs
npm run clean:install
overrideWarningsEnabled=false npm run cdk -- bootstrap --profile <PROFILE_NAME>
overrideWarningsEnabled=false npm run cdk -- deploy\
 --parameters DeployDemoUIParameter=No\
  --parameters SourceBucketsParameter=<MY_BUCKET>\
   --profile <PROFILE_NAME>

Custom domains

cd $MAIN_DIRECTORY/source/constructs
npm run clean:install
overrideWarningsEnabled=false npm run cdk -- bootstrap --profile <PROFILE_NAME>
overrideWarningsEnabled=false npm run cdk -- deploy --all\
 --parameters ServerlessImageHandlerStack:DeployDemoUIParameter=No\
  --parameters ServerlessImageHandlerStack:SourceBucketsParameter=<MY_BUCKET>\
   --context customDomain=<MY_DOMAIN>\
    --profile <PROFILE_NAME>

The first deployment with a custom domain requires verifying ownership, if not already verified. Until verified, the deployment will seem stuck at the Certificate create_in_progress step. Please see https://docs.aws.amazon.com/acm/latest/userguide/domain-ownership-validation.html for instructions. The solution will have created a Hosted zone for you custom domain, which you can view in the AWS Route 53 dashboard.

Note:

  • MY_BUCKET: name of an existing bucket or buckets in your account
  • PROFILE_NAME: name of an AWS CLI profile that has appropriate credentials for deploying in your preferred region
  • MY_DOMAIN: full domain to use as a Cloudfront alias, eg --context customDomain=x.example.com

See all parameters: Parameters reference

Automated deployments

For automated deployments with GitHub actions, see .github/workflows/pipeline-workflow.yml.

  1. Fork this repo
  2. Bootstrap locally if not already done
  3. Change if: github.repository_owner == 'GeKorm' to your user or organization name
  4. Add the following variables and secrets:

For further customization, such as using Origin Shield, please modify the pipeline workflow command.

Usage

The new URL scheme is https://<domain>/<s3-url-or-path-to-image>?edits=<edits>. The bucket and key are part of the URL unencoded. All other parameters like moved to the query string portion of the URL.

Basic example

// How to use edits https://docs.aws.amazon.com/solutions/latest/serverless-image-handler/create-and-use-image-requests.html#dynamically-resize-photos
const edits = {};

// Stringify and encode URI
// For s3 bucket "bucket" and image key "/folder/image.jpg":
const url = `https://example.cloudfront.net/bucket/folder/image.jpg?edits=${encodeURIComponent(
  JSON.stringify(edits),
)}`;

Other examples

The image's full S3 URL can be used. This is a non-exhaustive list of accepted formats

Please open an issue if your preferred S3 URL format isn't supported.

Query parameters

Key Value
signature string
effort number (Default: 4, see Sharp options.effort)
outputFormat ImageFormatTypes
edits encodeURIComponent(JSON.stringify(edits))
headers encodeURIComponent(JSON.stringify(headers))

As an alternative to encodeURIComponent you can use URL or URLSearchParams

const url = new URL("https://cdn.example.com/bucket/image.jpg");
url.searchParams.set("outputFormat", "webp");
url.searchParams.set("edits", JSON.stringify(edits));

console.log(url.toString());
// https://cdn.example.com/bucket/image.jpg?outputFormat=webp&edits=%7B%22

// or equivalent
const params = new URLSearchParams();
params.set("outputFormat", "webp");
params.set("edits", JSON.stringify(edits));

console.log("https://cdn.example.com/bucket/image.jpg?" + params.toString());
// https://cdn.example.com/bucket/image.jpg?outputFormat=webp&edits=%7B%22

Thumbor and Rewrites

Thumbor and the Rewrite feature may work, but are not supported. Please use the original solution if required.

Configuration reference

Required in bold

Cloudformation

--parameters flag

These parameters can be added using the --parameters ServerlessImageHandlerStack:<PARAMETER> command line flag.

Name Type Default
CorsEnabledParameter
Would you like to enable Cross-Origin Resource Sharing (CORS) for the image handler API? Select 'Yes' if so.
String
YesNo
No
CorsOriginParameter
If you selected 'Yes' above, please specify an origin value here. A wildcard (*) value will support any origin. We recommend specifying an origin (i.e. https://example.domain) to restrict cross-site access to your API.
String *
SourceBucketsParameter
(Required) List the buckets (comma-separated) within your account that contain original image files. If you plan to use Thumbor or Custom image requests with this solution, the source bucket for those requests will be the first bucket listed in this field.
String defaultBucket, bucketNo2, bucketNo3, ...
DeployDemoUIParameter
Would you like to deploy a demo UI to explore the features and capabilities of this solution? This will create an additional Amazon S3 bucket and Amazon CloudFront distribution in your account. NOTE: The demo UI doesn't work with this fork, select "No".
String
YesNo
Yes
LogRetentionPeriodParameter
This solution automatically logs events to Amazon CloudWatch. Select the amount of time for CloudWatch logs from this solution to be retained (in days).
Number
13571430609012015018036540054573118273653
1
AutoWebPParameter
Would you like to enable automatic WebP based on accept headers? Select 'Yes' if so.
String
YesNo
No
EnableSignatureParameter
Would you like to enable the signature? If so, select 'Yes' and provide SecretsManagerSecret and SecretsManagerKey values.
String
YesNo
No
SecretsManagerSecretParameter
The name of AWS Secrets Manager secret. You need to create your secret under this name.
String ­
SecretsManagerKeyParameter
The name of AWS Secrets Manager secret key. You need to create secret key with this key name. The secret value would be used to check signature.
String ­
EnableDefaultFallbackImageParameter
Would you like to enable the default fallback image? If so, select 'Yes' and provide FallbackImageS3Bucket and FallbackImageS3Key values.
String
YesNo
No
FallbackImageS3BucketParameter
The name of the Amazon S3 bucket which contains the default fallback image. e.g. my-fallback-image-bucket
String ­
FallbackImageS3KeyParameter
The name of the default fallback image object key including prefix. e.g. prefix/image.jpg
String ­
CloudFrontPriceClassParameter
The AWS CloudFront price class to use. For more information see: Cloudfront documentation
String
PriceClass_AllPriceClass_200PriceClass_100
PriceClass_All

Context

source/constructs/cdk.json

These parameters can be added under context in cdk.json, or using the --context command line flag.

Name Type Default
customDomain
Alternative domain name for this distribution. For more information, see Cloudfront documentation
String ­
originShieldEnabled
Enable Origin Shield to improve cache hit ratio and performance. For more information, see Origin Shield documentation
String
YesNo
No
originShieldRegion
Must be specified if Origin Shield is not supported in your AWS_REGION. See Origin Shield regions
String process.env.AWS_REGION

Environment variables

Name Type Default
AWS_REGION
Deploy the solution to this region. Supported regions
String us-east-1

License

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0

aws-sih's People

Contributors

aassadza avatar beomseoklee avatar decafdev avatar dependabot[bot] avatar dougtoppin avatar evanwieren avatar fisenkodv avatar g-lenz avatar gekorm avatar georgebearden avatar gsingh04 avatar hnishar avatar hyandell avatar ihmaws avatar kamyarz-aws avatar shsenior avatar simonkrol avatar stevemorad avatar tomnight avatar

Watchers

 avatar

Forkers

lindar-joy

aws-sih's Issues

Custom domain only works in us-east-1

Problem

When deploying with a custom domain, to a region other than us-east-1 we get the following error:

The specified SSL certificate doesn't exist, isn't in us-east-1 region, isn't valid, or doesn't include a valid certificate chain.

That's because the Certificate must be in us-east-1 for Cloudfront.

Solution

Unfortunately there's currently no way to specify the region in the Construct. We need to create a separate stack for it. See aws/aws-cdk#9274 for more info, and https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_certificatemanager-readme.html#cross-region-certificates

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.