import express from 'express' ; import { getFirestore } from 'firebase-admin/firestore' ; import * as functions from 'firebase-functions' ; import fetch from 'node-fetch' ; import url , { URL } from 'url' ; const app = express ( ) ; const getSiteDomain = async ( ) => { const doc = await getFirestore ( ) . collection ( 'config' ) . doc ( 'site' ) . get ( ) ; return doc . data ( ) . domain ; } ; const getRendertronServer = async ( ) => { const doc = await getFirestore ( ) . collection ( 'config' ) . doc ( 'rendertron' ) . get ( ) ; return doc . data ( ) . server ; } ; param { Object } request const generateUrl = async ( request ) => { return url . format ( { protocol : request . protocol , host : await getSiteDomain ( ) , pathname : request . originalUrl , } ) ; } ; param { String } userAgent const checkForBots = ( userAgent ) => { const botList = 'baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|slackbot|facebot|developers.google.com/+/web/snippet/' . toLowerCase ( ) ; return userAgent . toLowerCase ( ) . search ( botList ) !== - 1 ; } ; app . get ( '*' , async ( req , res ) => { const botResult = checkForBots ( req . headers [ 'user-agent' ] ) ; if ( botResult ) { const targetUrl = generateUrl ( req ) ; fetch ( `${ await getRendertronServer ( ) }/render/${ targetUrl }` ) . then ( ( res ) => res . text ( ) ) . then ( ( body ) => { res . set ( 'Cache-Control' , 'public, max-age=300, s-maxage=600' ) ; res . set ( 'Vary' , 'User-Agent' ) ; res . send ( body . toString ( ) ) ; } ) ; } else { const path = new URL ( './index.html' , import . meta . url ) . pathname ; res . sendFile ( path ) ; } } ) ; export const prerender = functions . https . onRequest ( app ) ;