Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Very basic user-agent based router for Now.sh, to be coupled with @now/static-build builds.
const https = require('https')
let cachedIndex = null
let cachedIndexHeaders = null
// Function to handle our OpenGraph tags
const handleOpenGraphUA = ['Twitterbot', 'Facebot', 'facebookexternalhit']
const handleOpenGraph = (req, res) => {
// Check if we're serving Twitter or Facebook bots
const requestUA = req.headers['user-agent']
const matchedUA = handleOpenGraphUA.filter(searchUA => ~requestUA.toLowerCase().indexOf(searchUA.toLocaleLowerCase()))
// Did we had any matches?
if (matchedUA.length > 0) {
(async (req, res) => {
// TODO: Fetch remote content, create OG <meta> tags, etc
})(req, res)
// Return true so we don't keep following the request chain
return true
} else {
// Else, return false and keep going on request chain
return false
}
}
module.exports = (req, res) => {
// We handle our User-Agent headers here
if (handleOpenGraph(req, res)) return
// Extract the requested host and define our index.html file
const requestedHost = req.headers.host
const responseResrc = `https://${requestedHost}/vue-index.html`
// Function to serve our cache
const serveCached = res => {
res.headers = cachedIndexHeaders
res.end(cachedIndex)
}
// Check for cache
if (!cachedIndex) {
// If not cached, fetch new data
https.get(responseResrc, function (response) {
// This will store our response body
let responseBody = ''
// Collect data from response
response.on('data', chunk => {
responseBody += chunk
})
// When finished downloading the body, save in cache and serve
response.on('end', () => {
cachedIndexHeaders = response.headers
cachedIndex = responseBody
serveCached(res)
})
})
} else {
// If cached, serve it directly
serveCached(res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.