From 44e3b9e4d2e7d143310b2eb1fefd7ee3082cd273 Mon Sep 17 00:00:00 2001 From: Nathan Woodburn Date: Wed, 18 Jun 2025 10:51:41 +1000 Subject: [PATCH] feat: Add analytics to ipfs pages --- server.js | 43 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 348f7af..84d3be4 100644 --- a/server.js +++ b/server.js @@ -30,6 +30,29 @@ const RESERVED_PATHS = [ // Serve static files app.use(express.static(path.join(__dirname, 'public'))); +// Helper function to inject tracking script into HTML content +function injectTrackingScript(content, mimeType) { + if (mimeType && mimeType.includes('text/html')) { + const trackingScript = ''; + + let htmlContent = content.toString(); + + // Try to inject before + if (htmlContent.includes('')) { + return htmlContent.replace('', `${trackingScript}`); + } + // Or try to inject before if no found + else if (htmlContent.includes('')) { + return htmlContent.replace('', `${trackingScript}`); + } + // Otherwise append to the end + else { + return htmlContent + trackingScript; + } + } + return content; +} + // Status endpoint app.get('/api/status', (req, res) => { res.json({ status: 'online', version: '1.0.0' }); @@ -75,8 +98,11 @@ app.get('/:domain', async (req, res, next) => { res.setHeader('Content-Type', content.mimeType); } + // Inject tracking script if content is HTML + const processedContent = injectTrackingScript(content.data, content.mimeType); + // Return the content - res.send(content.data); + res.send(processedContent); } catch (error) { console.error('Error handling request:', error); res.status(500).json({ @@ -129,8 +155,11 @@ app.get('/:domain/*', async (req, res, next) => { res.setHeader('Content-Type', content.mimeType); } + // Inject tracking script if content is HTML + const processedContent = injectTrackingScript(content.data, content.mimeType); + // Return the content - res.send(content.data); + res.send(processedContent); } catch (error) { console.error('Error handling request:', error); res.status(500).json({ @@ -177,8 +206,11 @@ app.get('/hns/:domain/*', async (req, res) => { res.setHeader('Content-Type', content.mimeType); } + // Inject tracking script if content is HTML + const processedContent = injectTrackingScript(content.data, content.mimeType); + // Return the content - res.send(content.data); + res.send(processedContent); } catch (error) { console.error('Error handling request:', error); res.status(500).json({ @@ -223,8 +255,11 @@ app.get('/hns/:domain', async (req, res) => { res.setHeader('Content-Type', content.mimeType); } + // Inject tracking script if content is HTML + const processedContent = injectTrackingScript(content.data, content.mimeType); + // Return the content - res.send(content.data); + res.send(processedContent); } catch (error) { console.error('Error handling request:', error); res.status(500).json({