view-counter
v1.0.1
Published
A simple, embeddable view counter that generates dynamic SVG images showing page view counts
Maintainers
Readme
View Count
A simple, embeddable view counter badge for any website. Track page views and unique visitors with a beautiful two-tone SVG badge. Powered by Firebase.
Quick Start (Hosted Service)
The easiest way to use view-count is with the hosted service. Just embed an image tag on your page:
Track Page Views
<img src="https://view-count.cloudtion.com/views?fallback-id=cloudtion-github-view-count" alt="page view count" />Track Unique Visitors
<img src="https://view-count.cloudtion.com/visitors?color=blue&fallback-id=cloudtion-github-view-count" alt="page visitor count" />Customize Colors
Add a ?color= parameter to change the badge color:
<img src="https://view-count.example.com/views?color=blue" alt="views" />Available colors:
| Color | Preview |
|-------|---------|
| green (default) | |
|
blue | |
|
red | |
|
orange | |
|
yellow | |
|
purple | |
|
pink | |
|
cyan | |
|
gray | |
|
black | |
GitHub READMEs & Restricted Environments
GitHub (and some other platforms) strip the Referer header via their image proxy. Use the ?fallback-id= parameter:
The fallback-id is only used when no Referer header is present, so it can't be used to spoof counts on normal websites.
How It Works
- When the image loads, the counter reads the
Refererheader to identify which page the badge is embedded on (or usesfallback-idif no Referer is present) - Each unique page URL gets its own view/visitor count
- The badge is cached by the browser (default: 30 minutes) to prevent excessive counting
- Unique visitors are tracked by hashing IP + User-Agent
Self-Hosted (Library Usage)
Install view-count as a library to run your own counter service.
Installation
npm install view-countBasic Setup
import { createViewCounter } from 'view-count';
const counter = createViewCounter({
firebaseConfig: {
projectId: 'your-project-id',
clientEmail: '[email protected]',
privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n',
collectionName: 'view-counts', // optional, defaults to 'view-counts'
},
cacheTtlMs: 30 * 60 * 1000, // optional, defaults to 30 minutes
});
// Use with Express
app.get('/views', counter.handler);
app.get('/visitors', counter.handler);Express Example
import express from 'express';
import { createViewCounter } from 'view-count';
const app = express();
const counter = createViewCounter({
firebaseConfig: {
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY,
collectionName: 'view-counts',
},
});
// Badge endpoints
app.get('/views', counter.handler);
app.get('/visitors', counter.handler);
app.listen(3000);Vercel Serverless Example
// api/views.ts
import { createViewCounter } from 'view-count';
const counter = createViewCounter({
firebaseConfig: {
projectId: process.env.FIREBASE_PROJECT_ID!,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL!,
privateKey: process.env.FIREBASE_PRIVATE_KEY!,
collectionName: 'view-counts',
},
});
export default counter.handler;// api/visitors.ts
import { createViewCounter } from 'view-count';
const counter = createViewCounter({
firebaseConfig: {
projectId: process.env.FIREBASE_PROJECT_ID!,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL!,
privateKey: process.env.FIREBASE_PRIVATE_KEY!,
collectionName: 'view-counts',
},
});
export default counter.handler;Firebase Setup
- Create a Firebase project at console.firebase.google.com
- Enable Firestore Database in the Firebase console
- Go to Project Settings → Service Accounts → Generate new private key
- Use the downloaded JSON values for your config
Firestore Security Rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /view-counts/{document=**} {
allow read, write: if true;
}
}
}Note: For production, consider adding rate limiting or authentication.
API Reference
createViewCounter(options)
Creates a new view counter instance.
Options
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| firebaseConfig.projectId | string | Yes | - | Firebase project ID |
| firebaseConfig.clientEmail | string | Yes | - | Service account email |
| firebaseConfig.privateKey | string | Yes | - | Service account private key |
| firebaseConfig.collectionName | string | No | 'view-counts' | Firestore collection name |
| cacheTtlMs | number | No | 1800000 | Browser cache duration (ms) |
Returns
| Method | Description |
|--------|-------------|
| handler(req, res) | Express-compatible request handler |
| getStats(pageUrl) | Get stats for a page without incrementing |
| recordView(pageUrl, visitorId) | Manually record a view |
| preview(count, mode?, color?) | Generate SVG without recording |
Endpoints
The handler responds differently based on the URL path:
| Path | Badge Shows |
|------|-------------|
| /views | Total page views |
| /visitors | Unique visitors |
Both endpoints accept these query parameters:
?color=- Badge color (see available colors below)?fallback-id=- Page identifier for environments that strip Referer headers (e.g., GitHub)
Available Colors
import { COLORS } from 'view-count';
// COLORS = {
// green: "#4c1",
// blue: "#007ec6",
// red: "#e05d44",
// orange: "#fe7d37",
// yellow: "#dfb317",
// purple: "#9f7be1",
// pink: "#e85aad",
// gray: "#555",
// black: "#1a1a1a",
// cyan: "#24b9a7",
// }Deploy to Firebase
The easiest way to deploy your own instance is using Firebase Functions.
Prerequisites
Install Firebase CLI:
npm install -g firebase-toolsLogin to Firebase:
firebase loginCreate a Firebase project at console.firebase.google.com
Enable Firestore Database in the Firebase console
Deploy
Update
.firebasercwith your project ID:{ "projects": { "default": "your-project-id" } }Deploy:
npm run deploy
This deploys:
- Cloud Functions:
viewsandvisitorsendpoints - Firestore Rules: Allow read/write to
view-countscollection - Hosting: Landing page at your Firebase domain
Your Endpoints
After deployment, your endpoints will be available at your Firebase Hosting domain:
https://YOUR_PROJECT_ID.web.app/views
https://YOUR_PROJECT_ID.web.app/visitorsEmbed them on any page:
<img src="https://YOUR_PROJECT_ID.web.app/views" alt="views" />
<img src="https://YOUR_PROJECT_ID.web.app/visitors?color=blue" alt="visitors" />Local Testing
Test locally with the dev server:
npm run devDevelopment
# Clone the repo
git clone https://github.com/cloudtion/view-count.git
cd view-count
# Install dependencies
npm install
# Copy env file and add your Firebase credentials
cp .env.example .env
# Run dev server (with hot reload)
npm run dev
# Build for production
npm run buildEnvironment Variables
FB_PROJECT_ID=your-project-id
FB_CLIENT_EMAIL=your-service-account@your-project.iam.gserviceaccount.com
FB_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
FB_COLLECTION_NAME=view-counts
CACHE_TTL_MS=1800000
SERVER_PORT=3000License
MIT
