diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cfe7b7..106d9b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 12.0.1 (December 21, 2021) + +In this release we fixed a bug that could occur when using absolute image paths (When you use S3 as backend, you are not affected). +In addition you can now define a new input variable `next_image_base_origin` that can be used to resolve absolute image paths. + +When you set `next_image_base_origin = "https://example.com"` requests for an absolute image path (`/path/to/image.png`) are then resolved to the URL `https://example.com/path/to/image.png`. + +We also added a fully featured example how to use `next export` together with S3 and the image optimizer, check it out: [Statically exported Next.js app hosted on S3](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-next-js) + +- Add base origin setting ([#94](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/issues/94), [#95](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/pull/95)) +- Uses Image Optimizer module of [Next.js 12.0.1](https://github.com/vercel/next.js/releases/tag/v12.0.1) ([#81](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/pull/81)) + ## 12.0.0 (November 28, 2021) This release introduces a new package called [Pixel](https://github.com/milliHQ/pixel) that abstracts the image optimization stuff and makes it usable with platforms other than AWS Lambda. diff --git a/README.md b/README.md index cccaa66..9367290 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,9 @@ Then rebuild and redeploy your Next.js application to make use of the changed co ## Examples -- [Next.js + Vercel](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-next-js) +- [Statically exported Next.js app hosted on S3](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-next-js) + Use the image optimizer together with a statically exported Next.js app that is deployed to S3 and CloudFront. +- [Next.js + Vercel](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-next-js-export) Use the image optimizer together with a Next.js app deployed on Vercel. - [Existing CloudFront](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-existing-cloudfront) Use the image optimizer with an existing CloudFront distribution. @@ -133,11 +135,12 @@ Then rebuild and redeploy your Next.js application to make use of the changed co | lambda\_policy\_json | Additional policy document as JSON to attach to the Lambda Function role. | `string` | `""` | no | | lambda\_role\_permissions\_boundary | ARN of IAM policy that scopes aws\_iam\_role access for the lambda. | `string` | `null` | no | | lambda\_timeout | Max amount of time the worker Lambda Function has to return a response in seconds. Should not be more than 30 (Limited by API Gateway). | `number` | `30` | no | +| next\_image\_base\_origin | Base URL where requests for absolute image paths should be resolved to. Should not have a trailing slash. | `string` | `null` | no | | next\_image\_device\_sizes | Allowed device sizes that should be used for image optimization. | `list(number)` | `null` | no | | next\_image\_domains | Allowed origin domains that can be used for fetching images. | `list(string)` | `[]` | no | | next\_image\_formats | If the Accept head matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match, the Image Optimization API will fallback to the original image's format. | `list(string)` |
[
"image/webp"
]
| no | | next\_image\_image\_sizes | Allowed image sizes that should be used for image optimization. | `list(number)` | `null` | no | -| next\_image\_version | Next.js version from where you want to use the image optimizer from. Supports semver ranges. | `string` | `"12.0.0"` | no | +| next\_image\_version | Next.js version from where you want to use the image optimizer from. Supports semver ranges. | `string` | `"12.0.1"` | no | | source\_bucket\_id | When your static files are deployed to a Bucket (e.g. with Terraform Next.js) the optimizer can pull the source from the bucket rather than over the internet. | `string` | `null` | no | | tags | Tag metadata to label AWS resources that support tags. | `map(string)` | `{}` | no | diff --git a/docs/assets/architecture.png b/docs/assets/architecture.png index 22765af..64228f7 100644 Binary files a/docs/assets/architecture.png and b/docs/assets/architecture.png differ diff --git a/examples/with-next-js-export/.gitignore b/examples/with-next-js-export/.gitignore new file mode 100644 index 0000000..1437c53 --- /dev/null +++ b/examples/with-next-js-export/.gitignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env.local +.env.development.local +.env.test.local +.env.production.local + +# vercel +.vercel diff --git a/examples/with-next-js-export/LICENSE b/examples/with-next-js-export/LICENSE new file mode 100644 index 0000000..a32647f --- /dev/null +++ b/examples/with-next-js-export/LICENSE @@ -0,0 +1,10 @@ +The MIT License (MIT) + +Copyright (c) 2021 Felix Haus (milliVolt infrastructure) +Copyright (c) 2021 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/examples/with-next-js-export/README.md b/examples/with-next-js-export/README.md new file mode 100644 index 0000000..a9891a1 --- /dev/null +++ b/examples/with-next-js-export/README.md @@ -0,0 +1,105 @@ +# Next.js export and S3 example + +This example shows how to use the image optimizer together with a statically exported Next.js HTML site that is hosted on AWS S3. + +> **Note:** The full example code is available on [GitHub](https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-next-js-export) + +## Features + +- ✅  [Statically exported Next.js](https://nextjs.org/docs/advanced-features/static-html-export) HTML site using `next export` +- ✅  Site hosted on [AWS S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html) +- ✅  Optimized caching with Amazon CloudFront +- ✅  [Serverless image optimization](https://github.com/milliHQ/terraform-aws-next-js-image-optimization) using CloudFront and AWS Lambda + +## Setup guide + +This guide walks you through the necessary steps to deploy the example to your own AWS account. + +### 0. Prerequisites + +The following software is required to follow this guide: + +- [Node.js 14+](https://nodejs.org/) +- [Terraform 1.0+](https://www.terraform.io/downloads) +- [AWS CLI](https://aws.amazon.com/cli/) + +### 1. Initialize project + +Download the files from the example app and initialize it in a new folder: + +```sh +npx create-next-app -e https://github.com/milliHQ/terraform-aws-next-js-image-optimization/tree/main/examples/with-next-js-export my-app +cd my-app +``` + +### 2. Create the required resources in your AWS account + +We use Terraform to create all the resources (S3 bucket, CloudFront distribution, image optimizer, etc.) in your AWS account. +For simplicity we use [AWS Access Keys](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html) for authentication, other authentication methods are [also available](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication). + +```sh +# Expose your AWS Access Keys to the current terminal session +export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE +export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + +terraform init # Only needed on the first time running Terraform + +terraform plan # (Optional) See what resources Terraform will create +terraform apply # Deploy the image optimizer module to your AWS account +``` + +After Terraform has successfully created all resources in your AWS account, you should see the following output on the terminal: + +```sh +> Apply complete! +> +> Outputs: +> +> domain = ".cloudfront.net" +> website_bucket_id = "next-image-optimizer-example-export" +``` + +### 3. Adjust Next.js config + +In the Next.js project, open the `next.config.js` file and add the following lines (Remember to replace `` with the output from the previous step): + +```diff +// next.config.js ++ const domainName = 'xxxxxxxxxxxxxxxxx.cloudfront.net'; +- const domainName = '.cloudfront.net'; +``` + +### 4. Build and export the Next.js site + +To create a static build of Next.js we need to run two commands. +`next build` builds the production site in the `.next/` folder. +[`next export`](https://nextjs.org/docs/advanced-features/static-html-export) then creates a static HTML export from your site that can be deployed to a static file hosting service like AWS S3. + +```sh +npm run build # Builds the Next.js site +npm run export # Prepares the +``` + +After running the two commands you should see a new folder named `out/` in your project, where the statically exported site is exported to. + +### 5. Upload the Next.js site to S3 + +To upload the content of the `out/` folder we use the [AWS CLI](https://aws.amazon.com/cli/). +Make sure to replace `` with the output from step 2 before running the command: + +```sh +aws s3 sync ./out s3:// +``` + +--- + +Your website should now be accessible on the CloudFront domain `.cloudfront.net` you got from step 2. +To update your site, simply repeat step 4. & 5 of this guide. + +## Caveats + +Please note that [not all features](https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features) of Next.js are supported when using `next export`. +In addition here are some things that should be taken into account when using this solution: + +- **When using JPEG images in the `/public` folder, always use the `.jpeg` (long) not the `.jpg` (short) extension for it.** + Next.js image component always requests the long extension `.jpeg`, since S3 cannot soft redirect `.jpg` to `.jpeg` the request for the image would fail otherwise. diff --git a/examples/with-next-js-export/app.css b/examples/with-next-js-export/app.css new file mode 100644 index 0000000..d26ed75 --- /dev/null +++ b/examples/with-next-js-export/app.css @@ -0,0 +1,19 @@ +body { + font-family: -apple-system, BlinkMacSystemFont, sans-serif; + margin: 0; + padding: 0; + background: black; + color: white; +} + +a { + cursor: pointer; + color: #0076ff; + text-decoration: none; + transition: all 0.2s ease; + border-bottom: 1px solid black; +} + +a:hover { + border-bottom: 1px solid #0076ff; +} diff --git a/examples/with-next-js-export/components/view-source.js b/examples/with-next-js-export/components/view-source.js new file mode 100644 index 0000000..5cdea3d --- /dev/null +++ b/examples/with-next-js-export/components/view-source.js @@ -0,0 +1,26 @@ +import { svg, arm } from './view-source.module.css'; + +const ViewSource = ({ pathname }) => ( + + + + + + + +); + +export default ViewSource; diff --git a/examples/with-next-js-export/components/view-source.module.css b/examples/with-next-js-export/components/view-source.module.css new file mode 100644 index 0000000..faca5af --- /dev/null +++ b/examples/with-next-js-export/components/view-source.module.css @@ -0,0 +1,48 @@ +.svg { + position: absolute; + top: 0; + right: 0; +} +.arm { + transform-origin: 130px 106px; +} + +.svg:hover .arm { + animation: wave 560ms ease-in-out; +} + +@keyframes wave { + 0% { + transform: rotate(0deg); + } + + 20% { + transform: rotate(-25deg); + } + + 40% { + transform: rotate(10deg); + } + + 60% { + transform: rotate(-25deg); + } + + 80% { + transform: rotate(10deg); + } + + 100% { + transform: rotate(0deg); + } +} + +@media (max-width: 500px) { + .svg:hover .arm { + animation: none; + } + + .svg:hover .arm { + animation: wave 560ms ease-in-out; + } +} diff --git a/examples/with-next-js-export/main.tf b/examples/with-next-js-export/main.tf new file mode 100644 index 0000000..2f8a428 --- /dev/null +++ b/examples/with-next-js-export/main.tf @@ -0,0 +1,202 @@ +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 3.0" + } + } +} + +# Main AWS region where the resources should be created in +provider "aws" { + region = "us-east-1" +} + +########## +# Settings +########## +variable "deployment_name" { + description = "Identifier that should be added to the resources created in AWS." + type = string + default = "next-image-optimizer-example-export" +} + +######################## +# Image Optimizer module +######################## +module "next_image_optimizer" { + source = "milliHQ/next-js-image-optimization/aws" + + # Prevent creation of the internal CloudFront distribution + cloudfront_create_distribution = false + + deployment_name = var.deployment_name + next_image_domains = ["assets.vercel.com"] + next_image_formats = ["image/avif", "image/webp"] +} + +########### +# S3 bucket +########### +resource "aws_s3_bucket" "website_bucket" { + bucket_prefix = var.deployment_name + acl = "public-read" + force_destroy = true + + cors_rule { + allowed_headers = ["Authorization", "Content-Length"] + allowed_methods = ["GET", "POST"] + allowed_origins = ["*"] + max_age_seconds = 3000 + } + + website { + index_document = "index.html" + error_document = "404/index.html" + } + + tags = { + Name = var.deployment_name + } +} + +data "aws_iam_policy_document" "public_bucket_access" { + statement { + actions = ["s3:GetObject"] + resources = ["${aws_s3_bucket.website_bucket.arn}/*"] + + principals { + type = "AWS" + identifiers = ["*"] + } + } +} + +resource "aws_s3_bucket_policy" "this" { + bucket = aws_s3_bucket.website_bucket.id + policy = data.aws_iam_policy_document.public_bucket_access.json +} + +######################### +# CloudFront distribution +######################### +data "aws_cloudfront_origin_request_policy" "managed_cors_s3_origin" { + name = "Managed-CORS-CustomOrigin" +} + +data "aws_cloudfront_cache_policy" "managed_caching_optimized_uncompressed" { + name = "Managed-CachingOptimized" +} + +resource "aws_cloudfront_distribution" "distribution" { + enabled = true + is_ipv6_enabled = true + comment = var.deployment_name + + default_cache_behavior { + allowed_methods = ["GET", "HEAD", "OPTIONS"] + cached_methods = ["GET", "HEAD", "OPTIONS"] + target_origin_id = "website-bucket" + + viewer_protocol_policy = "redirect-to-https" + compress = true + + origin_request_policy_id = data.aws_cloudfront_origin_request_policy.managed_cors_s3_origin.id + cache_policy_id = data.aws_cloudfront_cache_policy.managed_caching_optimized_uncompressed.id + } + + origin { + domain_name = aws_s3_bucket.website_bucket.website_endpoint + origin_id = "website-bucket" + + custom_origin_config { + http_port = "80" + https_port = "443" + origin_protocol_policy = "http-only" + origin_ssl_protocols = ["TLSv1", "TLSv1.1", "TLSv1.2"] + } + } + + # This is a generic dynamic to create the cache behavior for the image optimizer + dynamic "ordered_cache_behavior" { + for_each = [module.next_image_optimizer.cloudfront_cache_behavior] + + content { + path_pattern = ordered_cache_behavior.value["path_pattern"] + allowed_methods = ordered_cache_behavior.value["allowed_methods"] + cached_methods = ordered_cache_behavior.value["cached_methods"] + target_origin_id = ordered_cache_behavior.value["target_origin_id"] + + viewer_protocol_policy = ordered_cache_behavior.value["viewer_protocol_policy"] + compress = ordered_cache_behavior.value["compress"] + + origin_request_policy_id = ordered_cache_behavior.value["origin_request_policy_id"] + cache_policy_id = ordered_cache_behavior.value["cache_policy_id"] + } + } + + # This is a generic dynamic to create the origin for the image optimizer + dynamic "origin" { + for_each = [module.next_image_optimizer.cloudfront_origin] + + content { + domain_name = origin.value["domain_name"] + origin_id = origin.value["origin_id"] + + # Origin Shield + dynamic "origin_shield" { + for_each = lookup(origin.value, "origin_shield", null) != null ? [true] : [] + + content { + enabled = lookup(origin.value["origin_shield"], "enabled", false) + origin_shield_region = lookup(origin.value["origin_shield"], "origin_shield_region", null) + } + } + + # S3 origin + dynamic "s3_origin_config" { + for_each = lookup(origin.value, "s3_origin_config", null) != null ? [true] : [] + + content { + origin_access_identity = lookup(origin.value["s3_origin_config"], "origin_access_identity", null) + } + } + + # Custom origin + dynamic "custom_origin_config" { + for_each = lookup(origin.value, "custom_origin_config", null) != null ? [true] : [] + + content { + http_port = lookup(origin.value["custom_origin_config"], "http_port", null) + https_port = lookup(origin.value["custom_origin_config"], "https_port", null) + origin_protocol_policy = lookup(origin.value["custom_origin_config"], "origin_protocol_policy", null) + origin_ssl_protocols = lookup(origin.value["custom_origin_config"], "origin_ssl_protocols", null) + origin_keepalive_timeout = lookup(origin.value["custom_origin_config"], "origin_keepalive_timeout", null) + origin_read_timeout = lookup(origin.value["custom_origin_config"], "origin_read_timeout", null) + } + } + } + } + + viewer_certificate { + cloudfront_default_certificate = true + } + + restrictions { + geo_restriction { + restriction_type = "none" + } + } +} + +######### +# Outputs +######### + +output "website_bucket_id" { + value = aws_s3_bucket.website_bucket.id +} + +output "domain" { + value = aws_cloudfront_distribution.distribution.domain_name +} diff --git a/examples/with-next-js-export/next.config.js b/examples/with-next-js-export/next.config.js new file mode 100644 index 0000000..25a5371 --- /dev/null +++ b/examples/with-next-js-export/next.config.js @@ -0,0 +1,24 @@ +const domainName = '.cloudfront.net'; + +module.exports = (phase) => { + const isExport = phase === 'phase-export'; + + /** + * @type {import('next').NextConfig} + */ + const nextConfig = { + images: { + loader: isExport ? 'custom' : 'default', + domains: ['assets.vercel.com'], + formats: ['image/avif', 'image/webp'], + path: `https://${domainName}/_next/image`, + }, + + /** + * Using the tailingSlash option is recommended when exporting it to S3 + * since S3 is only able to rewrite routes to /index.html + */ + trailingSlash: true, + }; + return nextConfig; +}; diff --git a/examples/with-next-js-export/package.json b/examples/with-next-js-export/package.json new file mode 100644 index 0000000..1091966 --- /dev/null +++ b/examples/with-next-js-export/package.json @@ -0,0 +1,16 @@ +{ + "name": "tf-next-image", + "version": "1.0.0", + "scripts": { + "dev": "next dev", + "build": "next build", + "export": "next export", + "start": "next start" + }, + "dependencies": { + "next": "latest", + "react": "latest", + "react-dom": "latest" + }, + "license": "MIT" +} diff --git a/examples/with-next-js-export/pages/_app.js b/examples/with-next-js-export/pages/_app.js new file mode 100644 index 0000000..f85f222 --- /dev/null +++ b/examples/with-next-js-export/pages/_app.js @@ -0,0 +1,5 @@ +import '../app.css'; + +export default function MyApp({ Component, pageProps }) { + return ; +} diff --git a/examples/with-next-js-export/pages/background.js b/examples/with-next-js-export/pages/background.js new file mode 100644 index 0000000..d8d6576 --- /dev/null +++ b/examples/with-next-js-export/pages/background.js @@ -0,0 +1,25 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; +import { bgWrap, bgText } from '../styles.module.css'; + +const Background = () => ( +
+ +
+ Mountains +
+

+ Image Component +
+ as a Background +

+
+); + +export default Background; diff --git a/examples/with-next-js-export/pages/color.js b/examples/with-next-js-export/pages/color.js new file mode 100644 index 0000000..c9dbefc --- /dev/null +++ b/examples/with-next-js-export/pages/color.js @@ -0,0 +1,42 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; + +// Pixel GIF code adapted from https://stackoverflow.com/a/33919020/266535 +const keyStr = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +const triplet = (e1, e2, e3) => + keyStr.charAt(e1 >> 2) + + keyStr.charAt(((e1 & 3) << 4) | (e2 >> 4)) + + keyStr.charAt(((e2 & 15) << 2) | (e3 >> 6)) + + keyStr.charAt(e3 & 63); + +const rgbDataURL = (r, g, b) => + `data:image/gif;base64,R0lGODlhAQABAPAA${ + triplet(0, r, g) + triplet(b, 255, 255) + }/yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==`; + +const Color = () => ( +
+ +

Image Component With Color Data URL

+ Dog + Cat +
+); + +export default Color; diff --git a/examples/with-next-js-export/pages/index.js b/examples/with-next-js-export/pages/index.js new file mode 100644 index 0000000..7a22891 --- /dev/null +++ b/examples/with-next-js-export/pages/index.js @@ -0,0 +1,139 @@ +import styles from '../styles.module.css'; +import Image from 'next/image'; +import Link from 'next/link'; +import ViewSource from '../components/view-source'; +import vercel from '../public/vercel.png'; + +const Code = (p) => ; + +const Index = () => ( +
+ +
+

Image Component with Next.js

+

+ This page demonstrates the usage of the{' '} + + next/image + {' '} + component with live examples. +

+

+ This component is designed to{' '} + + automatically optimize + {' '} + images on-demand as the browser requests them. +

+
+

Layout

+

+ The layout property tells the image to respond differently + depending on the device size or the container size. +

+

+ Select a layout below and try resizing the window or rotating your + device to see how the image reacts. +

+ +
+

Placeholder

+

+ The placeholder property tells the image what to do while + loading. +

+

+ You can optionally enable a blur-up placeholder while the high + resolution image loads. +

+

+ Try it out below (you may need to disable cache in dev tools to see the + effect if you already visited): +

+ +
+

Internal Image

+

+ The following is an example of a reference to an internal image from the{' '} + public directory. +

+

+ This image is intentionally large so you have to scroll down to the next + image. +

+ Vercel logo +
+

External Image

+

+ The following is an example of a reference to an external image at{' '} + assets.vercel.com. +

+

+ External domains must be configured in next.config.js using + the domains property. +

+ Next.js logo +
+

Learn More

+

+ You can optionally configure a cloud provider, device sizes, and more! +

+

+ Checkout the{' '} + + Image Optimization documentation + {' '} + to learn more. +

+
+
+); + +export default Index; diff --git a/examples/with-next-js-export/pages/layout-fill.js b/examples/with-next-js-export/pages/layout-fill.js new file mode 100644 index 0000000..813dfba --- /dev/null +++ b/examples/with-next-js-export/pages/layout-fill.js @@ -0,0 +1,32 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; +import mountains from '../public/mountains.jpeg'; + +const Fill = () => ( +
+ +

Image Component With Layout Fill

+
+ Mountains +
+
+ Mountains +
+
+ Mountains +
+
+); + +export default Fill; diff --git a/examples/with-next-js-export/pages/layout-fixed.js b/examples/with-next-js-export/pages/layout-fixed.js new file mode 100644 index 0000000..ea0f422 --- /dev/null +++ b/examples/with-next-js-export/pages/layout-fixed.js @@ -0,0 +1,19 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; +import mountains from '../public/mountains.jpeg'; + +const Fixed = () => ( +
+ +

Image Component With Layout Fixed

+ Mountains +
+); + +export default Fixed; diff --git a/examples/with-next-js-export/pages/layout-intrinsic.js b/examples/with-next-js-export/pages/layout-intrinsic.js new file mode 100644 index 0000000..f5a1ea4 --- /dev/null +++ b/examples/with-next-js-export/pages/layout-intrinsic.js @@ -0,0 +1,19 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; +import mountains from '../public/mountains.jpeg'; + +const Intrinsic = () => ( +
+ +

Image Component With Layout Intrinsic

+ Mountains +
+); + +export default Intrinsic; diff --git a/examples/with-next-js-export/pages/layout-responsive.js b/examples/with-next-js-export/pages/layout-responsive.js new file mode 100644 index 0000000..d9c3c1b --- /dev/null +++ b/examples/with-next-js-export/pages/layout-responsive.js @@ -0,0 +1,19 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; +import mountains from '../public/mountains.jpeg'; + +const Responsive = () => ( +
+ +

Image Component With Layout Responsive

+ Mountains +
+); + +export default Responsive; diff --git a/examples/with-next-js-export/pages/placeholder.js b/examples/with-next-js-export/pages/placeholder.js new file mode 100644 index 0000000..b5596b8 --- /dev/null +++ b/examples/with-next-js-export/pages/placeholder.js @@ -0,0 +1,19 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; +import mountains from '../public/mountains.jpeg'; + +const PlaceholderBlur = () => ( +
+ +

Image Component With Placeholder Blur

+ Mountains +
+); + +export default PlaceholderBlur; diff --git a/examples/with-next-js-export/pages/shimmer.js b/examples/with-next-js-export/pages/shimmer.js new file mode 100644 index 0000000..7c2cf6d --- /dev/null +++ b/examples/with-next-js-export/pages/shimmer.js @@ -0,0 +1,39 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; + +const shimmer = (w, h) => ` + + + + + + + + + + + +`; + +const toBase64 = (str) => + typeof window === 'undefined' + ? Buffer.from(str).toString('base64') + : // eslint-disable-next-line no-undef + window.btoa(str); + +const Shimmer = () => ( +
+ +

Image Component With Shimmer Data URL

+ Mountains +
+); + +export default Shimmer; diff --git a/examples/with-next-js-export/public/cat.jpeg b/examples/with-next-js-export/public/cat.jpeg new file mode 100644 index 0000000..32a673a Binary files /dev/null and b/examples/with-next-js-export/public/cat.jpeg differ diff --git a/examples/with-next-js-export/public/dog.jpeg b/examples/with-next-js-export/public/dog.jpeg new file mode 100644 index 0000000..4209384 Binary files /dev/null and b/examples/with-next-js-export/public/dog.jpeg differ diff --git a/examples/with-next-js-export/public/mountains.jpeg b/examples/with-next-js-export/public/mountains.jpeg new file mode 100644 index 0000000..9d869a6 Binary files /dev/null and b/examples/with-next-js-export/public/mountains.jpeg differ diff --git a/examples/with-next-js-export/public/vercel.png b/examples/with-next-js-export/public/vercel.png new file mode 100644 index 0000000..cb137a9 Binary files /dev/null and b/examples/with-next-js-export/public/vercel.png differ diff --git a/examples/with-next-js-export/styles.module.css b/examples/with-next-js-export/styles.module.css new file mode 100644 index 0000000..2e3e92d --- /dev/null +++ b/examples/with-next-js-export/styles.module.css @@ -0,0 +1,50 @@ +.container { + padding: 4rem 1rem; +} + +.container p { + margin: 1.5rem 0; +} + +.card { + max-width: 60rem; + box-shadow: -10px 10px 80px rgba(255, 255, 255, 0.1); + border: 1px solid #333; + border-radius: 8px; + padding: 2rem; + margin: 0 auto; +} + +.inlineCode { + color: #be00ff; + font-size: 16px; + white-space: pre-wrap; +} + +.inlineCode::before, +.inlineCode::after { + content: '`'; +} + +.hr { + border: 0; + border-top: 1px solid #333; + margin: 1.5rem 0; +} + +.bgWrap { + position: fixed; + height: 100vh; + width: 100vw; + overflow: hidden; + z-index: -1; +} + +.bgText { + margin: 0; + font-size: 2rem; + line-height: 3rem; + text-align: center; + padding-top: 40vh; + text-shadow: 1px 1px 1px #3c5c5e; +} diff --git a/examples/with-next-js/next.config.js b/examples/with-next-js/next.config.js index a84f164..2316e83 100644 --- a/examples/with-next-js/next.config.js +++ b/examples/with-next-js/next.config.js @@ -1,6 +1,7 @@ module.exports = { images: { domains: ['assets.vercel.com'], + formats: ['image/avif', 'image/webp'], path: 'https://.cloudfront.net/_next/image', }, }; diff --git a/examples/with-next-js/pages/color.js b/examples/with-next-js/pages/color.js new file mode 100644 index 0000000..02e79f8 --- /dev/null +++ b/examples/with-next-js/pages/color.js @@ -0,0 +1,42 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; + +// Pixel GIF code adapted from https://stackoverflow.com/a/33919020/266535 +const keyStr = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +const triplet = (e1, e2, e3) => + keyStr.charAt(e1 >> 2) + + keyStr.charAt(((e1 & 3) << 4) | (e2 >> 4)) + + keyStr.charAt(((e2 & 15) << 2) | (e3 >> 6)) + + keyStr.charAt(e3 & 63); + +const rgbDataURL = (r, g, b) => + `data:image/gif;base64,R0lGODlhAQABAPAA${ + triplet(0, r, g) + triplet(b, 255, 255) + }/yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==`; + +const Color = () => ( +
+ +

Image Component With Color Data URL

+ Dog + Cat +
+); + +export default Color; diff --git a/examples/with-next-js/pages/index.js b/examples/with-next-js/pages/index.js index 858aa3b..7a22891 100644 --- a/examples/with-next-js/pages/index.js +++ b/examples/with-next-js/pages/index.js @@ -2,6 +2,7 @@ import styles from '../styles.module.css'; import Image from 'next/image'; import Link from 'next/link'; import ViewSource from '../components/view-source'; +import vercel from '../public/vercel.png'; const Code = (p) => ; @@ -20,7 +21,7 @@ const Index = () => (

This component is designed to{' '} - automatically optimizate + automatically optimize {' '} images on-demand as the browser requests them.

@@ -62,16 +63,47 @@ const Index = () => (
+

Placeholder

+

+ The placeholder property tells the image what to do while + loading. +

+

+ You can optionally enable a blur-up placeholder while the high + resolution image loads. +

+

+ Try it out below (you may need to disable cache in dev tools to see the + effect if you already visited): +

+ +

Internal Image

- The following is an example of a reference to an interal image from the{' '} + The following is an example of a reference to an internal image from the{' '} public directory.

This image is intentionally large so you have to scroll down to the next image.

- Vercel logo + Vercel logo

External Image

diff --git a/examples/with-next-js/pages/layout-fill.js b/examples/with-next-js/pages/layout-fill.js index 51a7344..1148208 100644 --- a/examples/with-next-js/pages/layout-fill.js +++ b/examples/with-next-js/pages/layout-fill.js @@ -1,22 +1,18 @@ import Image from 'next/image'; import ViewSource from '../components/view-source'; +import mountains from '../public/mountains.jpg'; const Fill = () => (

Image Component With Layout Fill

- Mountains + Mountains
Mountains @@ -24,7 +20,7 @@ const Fill = () => (
Mountains (
@@ -7,7 +8,7 @@ const Fixed = () => (

Image Component With Layout Fixed

Mountains (
@@ -7,7 +8,7 @@ const Intrinsic = () => (

Image Component With Layout Intrinsic

Mountains (
@@ -7,7 +8,7 @@ const Responsive = () => (

Image Component With Layout Responsive

Mountains ( +
+ +

Image Component With Placeholder Blur

+ Mountains +
+); + +export default PlaceholderBlur; diff --git a/examples/with-next-js/pages/shimmer.js b/examples/with-next-js/pages/shimmer.js new file mode 100644 index 0000000..7c2cf6d --- /dev/null +++ b/examples/with-next-js/pages/shimmer.js @@ -0,0 +1,39 @@ +import Image from 'next/image'; +import ViewSource from '../components/view-source'; + +const shimmer = (w, h) => ` + + + + + + + + + + + +`; + +const toBase64 = (str) => + typeof window === 'undefined' + ? Buffer.from(str).toString('base64') + : // eslint-disable-next-line no-undef + window.btoa(str); + +const Shimmer = () => ( +
+ +

Image Component With Shimmer Data URL

+ Mountains +
+); + +export default Shimmer; diff --git a/examples/with-next-js/public/cat.jpg b/examples/with-next-js/public/cat.jpg new file mode 100644 index 0000000..32a673a Binary files /dev/null and b/examples/with-next-js/public/cat.jpg differ diff --git a/examples/with-next-js/public/dog.jpg b/examples/with-next-js/public/dog.jpg new file mode 100644 index 0000000..4209384 Binary files /dev/null and b/examples/with-next-js/public/dog.jpg differ diff --git a/main.tf b/main.tf index 5324c07..7390b5f 100644 --- a/main.tf +++ b/main.tf @@ -27,6 +27,7 @@ module "image_optimizer" { environment_variables = { NODE_ENV = "production" + TF_NEXTIMAGE_BASE_ORIGIN = var.next_image_base_origin TF_NEXTIMAGE_DOMAINS = jsonencode(var.next_image_domains) TF_NEXTIMAGE_DEVICE_SIZES = var.next_image_device_sizes != null ? jsonencode(var.next_image_device_sizes) : null TF_NEXTIMAGE_FORMATS = jsonencode(var.next_image_formats) @@ -143,7 +144,7 @@ locals { # e.g. example.com/_next/image?url=/image.png, would fetch the # image from example.com/image.png.name # Not used if the images are fetched from S3 bucket. - cloudfront_allowed_headers = var.source_bucket_id != null ? ["accept"] : sort(["accept", "referer"]) + cloudfront_allowed_headers = var.source_bucket_id == null && var.next_image_base_origin == null ? sort(["accept", "referer"]) : ["accept"] # CloudFront origin diff --git a/variables.tf b/variables.tf index 23670cc..8fad0d6 100644 --- a/variables.tf +++ b/variables.tf @@ -4,7 +4,13 @@ variable "next_image_version" { description = "Next.js version from where you want to use the image optimizer from. Supports semver ranges." type = string - default = "12.0.0" + default = "12.0.1" +} + +variable "next_image_base_origin" { + description = "Base URL where requests for absolute image paths should be resolved to. Should not have a trailing slash." + type = string + default = null } variable "next_image_domains" {