@@ -13,19 +13,23 @@ interface CloudFrontPropsDistribution {
13
13
requestEdgeFunction : cloudfront . experimental . EdgeFunction
14
14
responseEdgeFunction : cloudfront . experimental . EdgeFunction
15
15
cacheConfig : CacheConfig
16
+ imageTTL ?: number
16
17
}
17
18
19
+ const OneDayCache = Duration . days ( 1 )
18
20
const OneMonthCache = Duration . days ( 30 )
19
21
const NoCache = Duration . seconds ( 0 )
22
+
20
23
const defaultNextQueries = [ '_rsc' ]
21
24
const defaultNextHeaders = [ 'Cache-Control' ]
25
+ const imageQueries = [ 'w' , 'h' , 'url' , 'q' ]
22
26
export class CloudFrontDistribution extends Construct {
23
27
public readonly cf : cloudfront . Distribution
24
28
25
29
constructor ( scope : Construct , id : string , props : CloudFrontPropsDistribution ) {
26
30
super ( scope , id )
27
31
28
- const { staticBucket, requestEdgeFunction, responseEdgeFunction, cacheConfig } = props
32
+ const { staticBucket, requestEdgeFunction, responseEdgeFunction, cacheConfig, ebAppDomain , imageTTL } = props
29
33
30
34
const splitCachePolicy = new cloudfront . CachePolicy ( this , 'SplitCachePolicy' , {
31
35
cachePolicyName : `${ id } -SplitCachePolicy` ,
@@ -53,7 +57,23 @@ export class CloudFrontDistribution extends Construct {
53
57
minTtl : OneMonthCache
54
58
} )
55
59
60
+ const imageTTLValue = imageTTL ? Duration . seconds ( imageTTL ) : OneDayCache
61
+
62
+ const imageCachePolicy = new cloudfront . CachePolicy ( this , 'ImageCachePolicy' , {
63
+ cachePolicyName : `${ id } -ImageCachePolicy` ,
64
+ queryStringBehavior : cloudfront . CacheQueryStringBehavior . allowList ( ...imageQueries ) ,
65
+ cookieBehavior : cloudfront . CacheCookieBehavior . none ( ) ,
66
+ headerBehavior : cloudfront . CacheHeaderBehavior . allowList ( ...defaultNextHeaders ) ,
67
+ defaultTtl : imageTTLValue ,
68
+ maxTtl : imageTTLValue ,
69
+ minTtl : imageTTLValue
70
+ } )
71
+
56
72
const s3Origin = new origins . S3Origin ( staticBucket )
73
+ const nextServerOrigin = new origins . HttpOrigin ( ebAppDomain , {
74
+ protocolPolicy : cloudfront . OriginProtocolPolicy . HTTP_ONLY ,
75
+ httpPort : 80
76
+ } )
57
77
58
78
this . cf = new cloudfront . Distribution ( this , id , {
59
79
defaultBehavior : {
@@ -82,6 +102,10 @@ export class CloudFrontDistribution extends Construct {
82
102
] ,
83
103
cachePolicy : splitCachePolicy
84
104
} ,
105
+ '/_next/image*' : {
106
+ origin : nextServerOrigin ,
107
+ cachePolicy : imageCachePolicy
108
+ } ,
85
109
'/_next/*' : {
86
110
origin : s3Origin ,
87
111
cachePolicy : longCachePolicy
0 commit comments