Skip to content

Commit

Permalink
Merge pull request #382 from aligent/feature/prerender_cf_cache_control
Browse files Browse the repository at this point in the history
Prerender CloudFront cache control
  • Loading branch information
krishanthisera authored Jul 25, 2022
2 parents d28763f + 8844f46 commit 3c6d063
Show file tree
Hide file tree
Showing 8 changed files with 622 additions and 4,608 deletions.
5,131 changes: 532 additions & 4,599 deletions package-lock.json

Large diffs are not rendered by default.

23 changes: 17 additions & 6 deletions packages/prerender-proxy/README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
# Prerender Proxy
This library provides two function constructs and a construct that creates two Lambda@Edge functions to use prerender.io as a Cloudfront Origin for site indexers (Google, Bing, etc).

This library provides two function constructs and a construct that creates two Lambda@Edge functions to use prerender.io as a Cloudfront Origin for site indexers (Google, Bing, etc).

The `prerender-check` is a `viewer-request` function that will check if a requester is from a indexer and if it is adds a header so that the second function `prerender` (`origin-request`) will alter the origin to prerender.

The `prerender` will function also make a HEAD request to a nominated backend to detect 301 and 302 redirects and if so forward them on to the frontend. This ensures that your SEO rankings are not penalized by having multiple pages at the same URL.

These functions are intended to be added to an existing Cloudfront

## Cache Control

The intention of `cache-control` function is to avoid/control CloudFront Caches for `prerender` bot.
This function to be associated with CloudFront's `origin response`

## Props
`redirectBackendOrigin`: The backend origin to make the HEAD request to.
`redirectFrontendHost`: This hostname is used to replace the backend host for any redirects that contain the backend host.
`prerenderToken`: Your prerender.io authentication token
`prerenderUrl`: The URL of your Prerender service (optional: defaults to prerender.io)
`pathPrefix`: A prefix path (optional)

`redirectBackendOrigin`: The backend origin to make the HEAD request to
`redirectFrontendHost`: This hostname is used to replace the backend host for any redirects that contain the backend host
`prerenderToken`: Your prerender.io authentication token
`prerenderUrl`: The URL of your Prerender service (optional: defaults to prerender.io)
`pathPrefix`: A prefix path (optional)
`cacheControlProps.cacheKey`: An optional parameter, which is to set `PRERENDER_CACHE_KEY` to be used in *[prerender CloudFront cache control function]*
`cacheControlProps.maxAge`: An optional parameter, which is to set `PRERENDER_CACHE_MAX_AGE` to be used in *[prerender CloudFront cache control function]*

[prerender CloudFront cache control function]:lib/handlers/cache-control.ts
3 changes: 2 additions & 1 deletion packages/prerender-proxy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ import { PrerenderLambda } from "./lib/prerender-lambda-construct";
import { PrerenderFunction } from "./lib/prerender-construct";
import { PrerenderCheckFunction } from "./lib/prerender-check-construct";
import { ErrorResponseFunction } from "./lib/error-response-construct";
import { CloudFrontCacheControl } from "./lib/prerender-cf-cache-control-construct"

export { PrerenderLambda, PrerenderFunction, PrerenderCheckFunction, ErrorResponseFunction };
export { PrerenderLambda, PrerenderFunction, PrerenderCheckFunction, ErrorResponseFunction, CloudFrontCacheControl };
21 changes: 21 additions & 0 deletions packages/prerender-proxy/lib/handlers/cache-control.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'source-map-support/register';
import { CloudFrontResponseEvent, CloudFrontResponse } from 'aws-lambda';
/*
Prerender cache control function
Consider associate this function as *origin response* function
*/
export const handler = async (event: CloudFrontResponseEvent): Promise<CloudFrontResponse> => {
const cacheKey = process.env.PRERENDER_CACHE_KEY || 'x-prerender-requestid';
const cacheMaxAge = process.env.PRERENDER_CACHE_MAX_AGE || '0';
let response = event.Records[0].cf.response;

if (response.headers[`${cacheKey}`]) {
response.headers['Cache-Control'] = [
{
key: 'Cache-Control',
value: `max-age=${cacheMaxAge}`
}
]
}
return response;
}
5 changes: 4 additions & 1 deletion packages/prerender-proxy/lib/handlers/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
"sourceMap": true,
"target": "es2017",
"outDir": "lib",
"typeRoots": ["./types", "../node_modules/@types"]
"typeRoots": ["./types", "../node_modules/@types"],
"types": [
"node"
]
},
"include": ["./**/*.ts"],
"exclude": [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Construct } from "@aws-cdk/core";
import { Bundling } from '@aws-cdk/aws-lambda-nodejs/lib/bundling';
import { Runtime } from '@aws-cdk/aws-lambda';
import { experimental } from '@aws-cdk/aws-cloudfront';
import { EdgeFunction } from "@aws-cdk/aws-cloudfront/lib/experimental";

export interface CloudFrontCacheControlOptions {
cacheKey?: string,
maxAge?: Number,
}

export class CloudFrontCacheControl extends Construct {
readonly edgeFunction: EdgeFunction;

constructor(scope: Construct, id: string, options?: CloudFrontCacheControlOptions) {
super(scope, id);

this.edgeFunction = new experimental.EdgeFunction(
this,
'PrerenderCloudFrontCacheControl',
{
code: Bundling.bundle({
entry: `${__dirname}/handlers/cache-control.ts`,
runtime: Runtime.NODEJS_14_X,
sourceMap: true,
projectRoot: `${__dirname}/handlers/`,
depsLockFilePath: `${__dirname}/handlers/package-lock.json`,
// Define options replace values at build time so we can use environment variables to test locally
// and replace during build/deploy with static values. This gets around the lambda@edge limitation
// of no environment variables at runtime.
define: {
'process.env.PRERENDER_CACHE_KEY': JSON.stringify(options?.cacheKey ?? 'x-prerender-requestid'),
'process.env.PRERENDER_CACHE_MAX_AGE': JSON.stringify(String(options?.maxAge) ?? '0'),
}
}),
runtime: Runtime.NODEJS_14_X,
handler: 'index.handler',
}
);
}
}
4 changes: 4 additions & 0 deletions packages/prerender-proxy/lib/prerender-lambda-construct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ import { Construct, CfnOutput } from '@aws-cdk/core';
import { PrerenderFunction } from './prerender-construct';
import { PrerenderCheckFunction } from './prerender-check-construct';
import { ErrorResponseFunction } from './error-response-construct';
import { CloudFrontCacheControl, CloudFrontCacheControlOptions } from "./prerender-cf-cache-control-construct";

export interface PrerenderLambdaProps {
prerenderToken: string
exclusionExpression?: string
cacheControlProps?: CloudFrontCacheControlOptions
}

export class PrerenderLambda extends Construct {

readonly prerenderCheckFunction:PrerenderCheckFunction
readonly prerenderFunction:PrerenderFunction
readonly errorResponseFunction:ErrorResponseFunction
readonly cacheControlFunction:CloudFrontCacheControl

constructor(scope: Construct, id: string, props: PrerenderLambdaProps) {
super(scope, id);
Expand All @@ -23,5 +26,6 @@ export class PrerenderLambda extends Construct {

this.errorResponseFunction = new ErrorResponseFunction(this, 'ErrorResponse', {});

this.cacheControlFunction = new CloudFrontCacheControl(this, 'PrerenderCloudFrontCacheControl', props.cacheControlProps)
}
}
2 changes: 1 addition & 1 deletion packages/prerender-proxy/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"devDependencies": {
"@aws-cdk/assert": "^1.111.0",
"@types/jest": "^26.0.21",
"@types/node": "10.17.27",
"@types/node": "^10.17.60",
"jest": "^26.4.2",
"ts-jest": "^26.5.4",
"ts-node": "^10.0.0",
Expand Down

0 comments on commit 3c6d063

Please sign in to comment.