import { APIGatewayProxyResultV2, APIGatewayProxyHandlerV2 } from 'aws-lambda'; import { ALBHandler, ALBResult } from 'aws-lambda'; import { APIGatewayPageHandler, ALBPageHandler } from './compatLayer.js'; // @ts-ignore import PrerenderManifestJson from './prerender-manifest.json'; // @ts-ignore import ManifestJson from './manifest.json'; // @ts-ignore import RoutesManifestJson from './routes-manifest.json'; import { DefaultHandlerManifest, RoutesManifest, StaticResult, } from '../types'; import type { Readable } from 'stream'; import { getRewritePath } from './routing/rewriter.js'; /** * Return public file from S3 bucket when it's in the publicFiles key in the manifest */ const handlePublicFile = async (uri: string): Promise => { const { BUCKET_NAME, BUCKET_REGION } = process.env as Record; const key = `public${uri}`; console.log(`Trying to access bucket ${BUCKET_NAME} with key ${key}`); const { S3Client } = await import('@aws-sdk/client-s3/S3Client'); const s3 = new S3Client({ region: BUCKET_REGION }); const { GetObjectCommand } = await import( '@aws-sdk/client-s3/commands/GetObjectCommand' ); /** * Quick workaround to return proper woff2 mimetype */ const setContentType = (key: string) => key.endsWith('woff2') && 'font/woff2' const params = { Bucket: BUCKET_NAME, Key: key, }; const { Body, ContentType, ContentLength } = await s3.send(new GetObjectCommand(params)); const getStream = await import('get-stream'); const bodyString = await getStream.default(Body as Readable); const length = Math.max(bodyString.length, ContentLength || 0) return { statusCode: 200, headers: { 'content-type': setContentType(key) || ContentType as string, 'content-length': length.toString() }, body: bodyString, }; }; /** * Return static page from S3 bucket when page is either a nonDynamic route or a prerendered page. */ const handleStaticPage = async (uri: string): Promise => { const pageName = uri === '/' ? '/index' : uri; const { BUCKET_NAME, BUCKET_REGION } = process.env as Record; console.log( `Trying to access bucket ${BUCKET_NAME} with path static-pages${pageName}.html` ); const { S3Client } = await import('@aws-sdk/client-s3/S3Client'); const s3 = new S3Client({ region: BUCKET_REGION }); const { GetObjectCommand } = await import( '@aws-sdk/client-s3/commands/GetObjectCommand' ); const params = { Bucket: BUCKET_NAME, Key: pageName.endsWith('.html') ? `static-pages${pageName}` : `static-pages${pageName}.html`, }; const { Body } = await s3.send(new GetObjectCommand(params)); const getStream = await import('get-stream'); const bodyString = await getStream.default(Body as Readable); return { statusCode: uri.includes('404') ? 404 : 200, headers: { 'content-type': 'text/html', }, body: bodyString, }; }; export const ApiGatewayHandler: APIGatewayProxyHandlerV2 = async ( event, context ): Promise => { let statusCode = 200; // Get current path with routing logic const rawUri = event.requestContext.http.path || event.rawPath let uri = normaliseUri(rawUri); const customRewrite = getRewritePath(rawUri, RoutesManifestJson, router(ManifestJson, RoutesManifestJson), uri) if (customRewrite) { // Has custom rewrite, update uri to appropriate rewritten page uri = normaliseUri(customRewrite) } const pagePath = router(ManifestJson, RoutesManifestJson)(uri); const isStaticPage = ManifestJson.pages.html.nonDynamic[uri]; const isPrerenderedPage = PrerenderManifestJson.routes[uri]; const isPublicFile = ManifestJson.publicFiles[uri]; if (isPublicFile) { // Public file, retrieve it from s3 return await handlePublicFile(uri); } if (isStaticPage || isPrerenderedPage) { // Public HTML page, retrieve it from s3 return await handleStaticPage(uri); } if (pagePath.endsWith('.html')) { // Router returns html page (might be 404 for example) return await handleStaticPage(pagePath.replace('pages', '')); } const page = require(`./${pagePath}`); // eslint-disable-line const returnPromise = await APIGatewayPageHandler(page)(event, context); return returnPromise; }; export const handler: ALBHandler = async ( event, context ): Promise => { // Get current path with routing logic const rawUri = event.path let uri = normaliseUri(rawUri); const customRewrite = getRewritePath(rawUri, RoutesManifestJson, router(ManifestJson, RoutesManifestJson), uri) if (customRewrite) { // Has custom rewrite, update uri to appropriate rewritten page uri = normaliseUri(customRewrite) } const pagePath = router(ManifestJson, RoutesManifestJson)(uri); const isStaticPage = ManifestJson.pages.html.nonDynamic[uri]; const isPrerenderedPage = PrerenderManifestJson.routes[uri]; const isPublicFile = ManifestJson.publicFiles[uri]; if (isPublicFile) { return await handlePublicFile(uri); } if (isStaticPage || isPrerenderedPage) { // Public HTML page, retrieve it from s3 return await handleStaticPage(uri); } if (pagePath.endsWith('.html')) { // Router returns html page (might be 404 for example) return await handleStaticPage(pagePath.replace('pages', '')); } const page = require(`./${pagePath}`); // eslint-disable-line const returnPromise = await ALBPageHandler(page)(event, context); return returnPromise; }; const basePath = RoutesManifestJson.basePath; const normaliseUri = (uri: string): string => { if (basePath) { if (uri.startsWith(basePath)) { uri = uri.slice(basePath.length); } else { // basePath set but URI does not start with basePath, return 404 return '/404'; } } // Remove trailing slash for all paths if (uri.endsWith('/')) { uri = uri.slice(0, -1); } // Empty path should be normalised to "/" as there is no Next.js route for "" return uri === '' ? '/' : uri; }; const normaliseDataRequestUri = ( uri: string, manifest: DefaultHandlerManifest ): string => { let normalisedUri = uri .replace(`/_next/data/${manifest.buildId}`, '') .replace('.json', ''); // Normalise to "/" for index data request normalisedUri = ['/index', ''].includes(normalisedUri) ? '/' : normalisedUri; return normalisedUri; }; const isDataRequest = (uri: string): boolean => uri.startsWith('/_next/data'); const router = ( manifest: DefaultHandlerManifest, routesManifest: RoutesManifest ): ((uri: string) => string) => { const { pages: { ssr, html }, apis, } = manifest; const allDynamicRoutes = { ...ssr.dynamic, ...html.dynamic, ...apis.dynamic }; return (uri: string): string => { let normalisedUri = uri; if (routesManifest?.i18n?.locales) { // Remove locale path from the file require path const locale = routesManifest.i18n.locales.find((item) => normalisedUri.includes(item) ); if (locale) { // Locale found, replace it and optionally the appending slash as well normalisedUri = normalisedUri.replace( RegExp(String.raw`${locale}\/?`, 'g'), '' ); } } if (isDataRequest(uri)) { normalisedUri = normaliseDataRequestUri(normalisedUri, manifest); } if (ssr.nonDynamic[normalisedUri]) { return ssr.nonDynamic[normalisedUri]; } if (apis.nonDynamic[normalisedUri]) { return apis.nonDynamic[normalisedUri]; } for (const route in allDynamicRoutes) { const { file, regex } = allDynamicRoutes[route]; const re = new RegExp(regex, 'i'); const pathMatchesRoute = re.test(normalisedUri); if (pathMatchesRoute) { return file; } } // only use the 404 page if the project exports it if (html.nonDynamic['/404'] !== undefined) { return 'pages/404.html'; } return 'pages/_error.js'; }; };