Created
February 18, 2021 22:03
-
-
Save tolu/df54a837f28784210906b847867a0e08 to your computer and use it in GitHub Desktop.
SPA meta-tag renderer (for fb bots etc)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
import puppeteer from 'puppeteer'; | |
import ua from 'useragent'; | |
const isBot = (agent: ua.Details) => { | |
return !agent.webkit && !agent.opera && !agent.ie && | |
!agent.chrome && !agent.safari && !agent.mobile_safari && | |
!agent.firefox && !agent.mozilla && !agent.android; | |
} | |
const app = express(); | |
app.use(async (req, res) => { | |
const renderUrl = `https://www.strim.no${req.path}`; | |
const agent = ua.is(req.headers['user-agent'] || ''); | |
console.log(`fetching: ${renderUrl}`, agent); | |
try { | |
const browser = await puppeteer.launch({ | |
'args' : [ | |
'--no-sandbox', | |
'--disable-setuid-sandbox' | |
] | |
}) | |
const page = await browser.newPage(); | |
await page.setUserAgent('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'); | |
await page.goto(renderUrl, { | |
waitUntil: 'networkidle0', | |
}); | |
const html = await page.evaluate(() => { | |
return document.documentElement.innerHTML; | |
}); | |
await browser.close(); | |
if (!isBot(agent)) { | |
res.contentType('text/plain'); | |
res.send(html); | |
} else { | |
res.send(html); | |
} | |
} catch (err) { | |
res.send(err) | |
} | |
}); | |
const port = process.env.PORT || 3000; | |
app.listen(port, () => { | |
console.log(`Web server is running at port ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment