Skip to content

Commit

Permalink
DO-1438: Use middified handlers with the prerender proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
krishanthisera committed Feb 2, 2023
1 parent 5d690c8 commit 9b2e9db
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 148 deletions.
27 changes: 7 additions & 20 deletions packages/prerender-proxy/lib/handlers/cache-control.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,8 @@
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;
import middy from "@middy/core";
import { PrerenderCacheControlHandler } from "@aligent/cdk-lambda-at-edge-handlers";

if (response.headers[`${cacheKey}`]) {
response.headers['Cache-Control'] = [
{
key: 'Cache-Control',
value: `max-age=${cacheMaxAge}`
}
]
}
return response;
}
/**
* Prerender Cache Control Handler
* @link https://github.com/aligent/cdk-constructs/blob/main/packages/lambda-at-edge-handlers/lib/cache-control.ts
*/
export const handler = middy(PrerenderCacheControlHandler);
59 changes: 8 additions & 51 deletions packages/prerender-proxy/lib/handlers/error-response.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,8 @@
import 'source-map-support/register';
import { CloudFrontRequest, CloudFrontResponseEvent, CloudFrontResponse } from 'aws-lambda';
import axios from "axios";
import { URL } from 'url';
import * as https from 'https';

const FRONTEND_HOST = process.env.FRONTEND_HOST;
const PATH_PREFIX = process.env.PATH_PREFIX;

// Create axios client outside of lambda function for re-use between calls
const instance = axios.create({
timeout: 1000,
// Don't follow redirects
maxRedirects: 0,
// Only valid response codes are 200
validateStatus: function (status) {
return status == 200;
},
// keep connection alive so we don't constantly do SSL negotiation
httpsAgent: new https.Agent({ keepAlive: true }),
});

export const handler = (event: CloudFrontResponseEvent): Promise<CloudFrontResponse|CloudFrontRequest> => {
let response = event.Records[0].cf.response;
let request = event.Records[0].cf.request;

if (response.status != '200' &&
! request.headers['x-request-prerender'] &&
request.uri != `${PATH_PREFIX}/index.html`) {

// Fetch default page and return body
return instance.get(`https://${FRONTEND_HOST}${PATH_PREFIX}/index.html`).then((res) => {
response.body = res.data;


response.headers['content-type'] = [{
key: 'Content-Type',
value: 'text/html'
}];

// Remove content-length if set as this may be the value from the origin.
delete response.headers['content-length']

return response;
}).catch((err) => {
return response
});
}

return Promise.resolve(response);
}
import middy from "@middy/core";
import { PrerenderErrorResponseHandler } from "@aligent/cdk-lambda-at-edge-handlers";

/**
* Prerender Error ResponseHandler
* @link https://github.com/aligent/cdk-constructs/blob/main/packages/lambda-at-edge-handlers/lib/error-response.ts
*/
export const handler = middy(PrerenderErrorResponseHandler);
68 changes: 62 additions & 6 deletions packages/prerender-proxy/lib/handlers/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion packages/prerender-proxy/lib/handlers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
"@types/aws-lambda": "^8.10.77",
"@types/node": "^15.12.4",
"axios": "^0.21.1",
"source-map-support": "^0.5.19"
"source-map-support": "^0.5.19",
"@middy/core": "^3.6.2",
"@aligent/cdk-lambda-at-edge-handlers": "^0.1.0"
},
"devDependencies": {
"@types/node": "^18.11.9"
}
}
35 changes: 8 additions & 27 deletions packages/prerender-proxy/lib/handlers/prerender-check.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,8 @@
import 'source-map-support/register';
import { CloudFrontRequest, CloudFrontRequestEvent } from 'aws-lambda';

const IS_BOT = /googlebot|chrome-lighthouse|lighthouse|adsbot\-google|Feedfetcher\-Google|bingbot|yandex|baiduspider|Facebot|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator/i;
const IS_FILE = /\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)$/i;

export const handler = async (event: CloudFrontRequestEvent): Promise<CloudFrontRequest> => {
let request = event.Records[0].cf.request;

// If the request is from a bot, is not a file and is not from prerender
// then set the x-request-prerender header so the origin-request lambda function
// alters the origin to prerender.io
if (!IS_FILE.test(request.uri)
&& IS_BOT.test(request.headers['user-agent'][0].value)
&& !request.headers['x-prerender']) {
request.headers['x-request-prerender'] = [
{
key: 'x-request-prerender',
value: 'true'
}
];

request.headers['x-prerender-host'] = [{ key: 'X-Prerender-Host', value: request.headers.host[0].value}];
}

return request;
}
import middy from "@middy/core";
import { PrerenderCheckHandler } from "@aligent/cdk-lambda-at-edge-handlers";

/**
* Prerender Check Handler
* @link https://github.com/aligent/cdk-constructs/blob/main/packages/lambda-at-edge-handlers/lib/prerender-check.ts
*/
export const handler = middy(PrerenderCheckHandler);
51 changes: 8 additions & 43 deletions packages/prerender-proxy/lib/handlers/prerender.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,8 @@
import 'source-map-support/register';
import { CloudFrontRequest, CloudFrontRequestEvent, CloudFrontResponse } from '@aws-cdk/aws-lambda';

const PRERENDER_TOKEN = process.env.PRERENDER_TOKEN;
const PATH_PREFIX = process.env.PATH_PREFIX;
const PRERENDER_URL = process.env.PRERENDER_URL;

export const handler = async (event: CloudFrontRequestEvent): Promise<CloudFrontResponse|CloudFrontRequest> => {
let request = event.Records[0].cf.request;

// viewer-request function will determine whether we prerender or not
// if we should we add prerender as our custom origin
if (request.headers['x-request-prerender']) {
// Cloudfront will alter the request for / to /index.html
// since it is defined as the default root object
// we do not want to do this when prerendering the homepage
if (request.uri === `${PATH_PREFIX}/index.html`) {
request.uri = `${PATH_PREFIX}/`;
}

request.origin = {
custom: {
domainName: PRERENDER_URL,
port: 443,
protocol: 'https',
readTimeout: 20,
keepaliveTimeout: 5,
sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],
path: '/https%3A%2F%2F' + request.headers['x-prerender-host'][0].value,
customHeaders: {
'x-prerender-token': [{
key: 'x-prerender-token',
value: PRERENDER_TOKEN
}]
}
}
};
} else {
request.uri = `${PATH_PREFIX}/index.html`;
}

return request;
}
import middy from "@middy/core";
import { PrerenderHandler } from "@aligent/cdk-lambda-at-edge-handlers";

/**
* Prerender Handler
* @link https://github.com/aligent/cdk-constructs/blob/main/packages/lambda-at-edge-handlers/lib/prerender.ts
*/
export const handler = middy(PrerenderHandler);

0 comments on commit 9b2e9db

Please sign in to comment.