β±οΈ 20 min read | π Beginner-Intermediate | π οΈ Vite + React + LunarCrush API
TL;DR: Build a Chrome extension that overlays real-time social analytics data, powered by the LunarCrush API, onto any webpage for instant insights into cryptocurrency trends.
- Build time: 60 minutes
- Lines of code: ~200 lines
- Key API:
/topic/{topic}/v1- ROI potential: $100-$1000+/month with 10-100 users offering a premium data feed.
Traders often rely on price charts and technical indicators to make informed decisions. But what if you could instantly access the collective wisdom of the crypto community directly within your browser? It turns out that social sentiment, as measured by LunarCrush's Galaxy Score, can often precede significant price movements. Ignoring this data is like driving a car while only looking in the rearview mirror.
Imagine browsing a news article about Bitcoin and instantly seeing its Galaxy Scoreβ’, social mentions, and sentiment analysis overlaid directly on the page. This extension provides that capability, offering real-time insights without switching tabs or manually searching for data. It's a powerful tool for gauging market sentiment and identifying potential opportunities before they become mainstream.
This article guides you through building a Chrome extension that leverages the LunarCrush API to overlay social analytics data onto any webpage. You'll learn how to fetch data, inject it into the DOM, and create a user-friendly interface. This project is valuable for traders, researchers, and anyone interested in understanding the social dynamics driving the crypto market. By building and offering this tool as a subscription service, you can tap into the growing demand for real-time social intelligence data.
π What is Galaxy Score?
Galaxy Score (0-100) measures social engagement strength by combining mentions,
interactions, sentiment, and contributor diversity. Scores above 70 often
correlate with increased market activity. Learn more
Prerequisites
Before diving into the code, ensure you have the following prerequisites in place:
- Node.js 18+: Make sure Node.js is installed on your system. You can download it from the official website (https://nodejs.org/).
- LunarCrush API key: You'll need an API key to access the LunarCrush data. You can create a free account and obtain an API key from the LunarCrush developer portal (https://lunarcrush.com/developers/api/authentication). Use code JAMAALBUILDS for 15% off.
- Basic React knowledge: Familiarity with React's component-based architecture is helpful.
Step 1: Setting Up the Vite Project
We'll use Vite to build our Chrome extension. Vite is a fast build tool that works great for Chrome extensions because it produces clean, bundled JavaScript files that Chrome can load.
Open your terminal and run the following command:
npm create vite@latest social-analytics-extension -- --template react-ts
Follow the prompts to initialize the project, then navigate to the project directory:
cd social-analytics-extension
Now, install the necessary dependencies:
npm install
npm install -D @types/chrome
This command installs the TypeScript definitions for Chrome extension APIs (@types/chrome), which provides type safety when interacting with the Chrome extension API.
Step 2: Creating the React Component
Now, let's create the React component that will display the social analytics data. This component will be injected into the webpage and will display the Galaxy Score, social mentions, and sentiment analysis.
Create a new file src/components/AnalyticsOverlay.tsx with the following content:
// src/components/AnalyticsOverlay.tsx
import React from 'react';
interface AnalyticsOverlayProps {
galaxyScore: string;
socialMentions: string;
sentiment: string;
}
const AnalyticsOverlay: React.FC<AnalyticsOverlayProps> = ({ galaxyScore, socialMentions, sentiment }) => {
return (
<div style={{
position: 'fixed',
top: '10px',
right: '10px',
backgroundColor: 'rgba(0, 0, 0, 0.9)',
color: 'white',
padding: '15px',
zIndex: 2147483647,
borderRadius: '8px',
fontFamily: 'system-ui, sans-serif',
fontSize: '14px',
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
minWidth: '200px',
}}>
<div style={{ fontWeight: 'bold', marginBottom: '10px', borderBottom: '1px solid #444', paddingBottom: '8px' }}>
π LunarCrush Analytics
</div>
<p style={{ margin: '5px 0' }}>Galaxy Score: <strong>{galaxyScore}</strong></p>
<p style={{ margin: '5px 0' }}>Social Mentions: <strong>{socialMentions}</strong></p>
<p style={{ margin: '5px 0' }}>Sentiment: <strong>{sentiment}</strong></p>
</div>
);
};
export default AnalyticsOverlay;
This code defines a React component that accepts galaxyScore, socialMentions, and sentiment as props. It renders these values in a fixed-position overlay. The zIndex: 2147483647 ensures the overlay appears above all other page elements. 2147483647 is 2Β³ΒΉ - 1 β the maximum value of a 32-bit signed integer. In CSS, z-index is stored as a 32-bit signed integer, so this is the highest possible z-index value. Using it ensures the overlay appears above everything else on any webpage.
Step 3: Creating the Content Script
The content script runs in the context of the webpage and is responsible for fetching data and injecting the React component. We'll use a background service worker to handle API calls (avoiding CORS issues).
Create a new file src/content.tsx:
// src/content.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import AnalyticsOverlay from './components/AnalyticsOverlay';
const injectOverlay = async () => {
// Request data from background script (avoids CORS)
const socialData = await chrome.runtime.sendMessage({ type: 'FETCH_DATA', topic: 'bitcoin' });
// Create container for React
const overlayContainer = document.createElement('div');
overlayContainer.id = 'lunarcrush-analytics-overlay';
document.body.appendChild(overlayContainer);
// React 18+ uses createRoot instead of ReactDOM.render
const root = createRoot(overlayContainer);
root.render(
<AnalyticsOverlay
galaxyScore={socialData?.galaxyScore || 'N/A'}
socialMentions={socialData?.socialMentions || 'N/A'}
sentiment={socialData?.sentiment || 'N/A'}
/>
);
};
// Run when page loads
injectOverlay();
Important: Content scripts can't make direct API calls to external domains due to CORS restrictions. Instead, we send a message to the background service worker, which has permission to make the API call.
Step 4: Creating the Background Service Worker
The background service worker handles API calls. It runs in the extension's context and has permissions to fetch from any allowed domain.
Create a new file src/background.ts:
// src/background.ts
const LUNARCRUSH_API_KEY = 'YOUR_API_KEY_HERE'; // Replace with your API key
chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
if (request.type === 'FETCH_DATA') {
fetchSocialData(request.topic).then(sendResponse);
return true; // Required for async response
}
});
async function fetchSocialData(topic: string) {
try {
const response = await fetch(
`https://lunarcrush.com/api4/public/topic/${topic}/v1`,
{ headers: { 'Authorization': `Bearer ${LUNARCRUSH_API_KEY}` } }
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
galaxyScore: data?.data?.galaxy_score?.toString() || 'N/A',
socialMentions: data?.data?.social_mentions_24h?.toLocaleString() || 'N/A',
sentiment: data?.data?.sentiment?.toString() || 'N/A',
};
} catch (error) {
console.error('Failed to fetch social data:', error);
return {
galaxyScore: 'Error',
socialMentions: 'Error',
sentiment: 'Error',
};
}
}
Note: In production, you'd want to store the API key securely using chrome.storage rather than hardcoding it. For development/testing, this approach works.
Step 5: Creating the Manifest File
The manifest file provides metadata about your Chrome extension. Create public/manifest.json:
{
"manifest_version": 3,
"name": "Social Analytics Overlay",
"version": "1.0",
"description": "Overlays LunarCrush social analytics data on webpages.",
"permissions": [
"activeTab",
"storage"
],
"host_permissions": [
"https://lunarcrush.com/*"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}
],
"background": {
"service_worker": "background.js",
"type": "module"
}
}
Key parts:
-
host_permissions: Required for the background script to fetch from LunarCrush API -
content_scripts: Injects our script into all webpages -
background.service_worker: Declares the background script
Step 6: Configuring Vite for Chrome Extension Build
Update vite.config.ts to build both the content script and background script:
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
export default defineConfig({
plugins: [react()],
build: {
rollupOptions: {
input: {
content: resolve(__dirname, 'src/content.tsx'),
background: resolve(__dirname, 'src/background.ts'),
},
output: {
entryFileNames: '[name].js',
chunkFileNames: '[name].js',
assetFileNames: '[name].[ext]',
},
},
outDir: 'dist',
emptyOutDir: true,
},
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
});
This configuration:
- Builds both content script and background script as separate entry points
- Outputs clean filenames without hashes (required for Chrome extensions)
- Places everything in the
distfolder
Step 7: Building and Loading the Extension
Build the extension:
npm run build
Copy the manifest to the dist folder:
cp public/manifest.json dist/
To load the extension in Chrome:
- Open Chrome and navigate to
chrome://extensions - Enable "Developer mode" in the top right corner
- Click "Load unpacked" and select the
distdirectory
The extension should now be loaded in Chrome.
Testing It Out
To test the extension:
-
Load the extension: Ensure it's loaded correctly in
chrome://extensions - Visit any webpage: Navigate to any page (e.g., a news article about Bitcoin)
- Check the overlay: You should see the analytics overlay in the top right corner
Example Output:
π LunarCrush Analytics
Galaxy Score: 75
Social Mentions: 12,345
Sentiment: 65
Troubleshooting:
- No overlay appears: Check the console for errors (right-click β Inspect β Console)
- "Error" shown: Check that your API key is correct and you have host_permissions set
- CORS errors: Make sure API calls are going through the background script, not the content script
ROI & First Customer Playbook
This Chrome extension offers a clear path to finding customers and providing valuable, real-time social intelligence data to crypto traders and researchers.
π First Customer Acquisition:
- Where to find them: r/CryptoCurrency, r/algotrading, Crypto Twitter, crypto trading communities.
- How to pitch it: "Stop wasting time manually checking social data. Get real-time Galaxy Score overlays directly in your browser."
π― Your SaaS Timeline
Day 1-2: Build & Polish
- Build the extension following this guide
- Add a simple landing page explaining the benefits
Day 3-4: Find Your Audience
- Post in r/CryptoCurrency, r/algotrading (focus on VALUE, not promotion)
- Share on Crypto Twitter with real insights from your tool
Day 5-7: Convert
- Offer 5 free beta spots in exchange for feedback
- After feedback, offer early-bird pricing (50% off first 10)
- Use testimonials for next wave
β FAQ
Q: Can I track multiple assets with this code?
A: Yes! Modify the topic variable in src/content.tsx or add a popup UI to let users select the topic.
Q: Why use a background script for API calls?
A: Content scripts run in the webpage's context, which has strict CORS policies. Background service workers run in the extension's context and can fetch from any domain listed in host_permissions.
Q: How do I store the API key securely?
A: Use chrome.storage.local.set({ apiKey: 'your-key' }) and retrieve it with chrome.storage.local.get('apiKey'). This keeps the key out of your source code.
π Glossary
- Galaxy Score: LunarCrush's proprietary 0-100 metric measuring social engagement strength.
- Social Mentions: The total number of times an asset is mentioned on social media.
- Sentiment: Aggregate positive/negative analysis from social posts (0-100).
- Content Script: JavaScript that runs in the context of web pages.
- Background Service Worker: A script that runs in the extension's context, handling events and API calls.
- Manifest V3: The current Chrome extension manifest format (required for new extensions).
What's Next
Here are some ideas for extending this Chrome extension:
- Add a popup UI: Create a popup that lets users configure topics, customize appearance, and set up alerts.
- Dynamic topic detection: Analyze the page content to automatically detect relevant crypto topics.
- Price alerts: Add notifications when Galaxy Score crosses certain thresholds.
- Historical charts: Show Galaxy Score trends over time using a small chart library.
- Multi-asset tracking: Display analytics for multiple assets detected on the page.
By building this Chrome extension, you've gained valuable experience with the LunarCrush API, React, and Chrome extension development. This project provides a solid foundation for creating more sophisticated social analytics tools.
Top comments (0)