Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

Count Visits

Get code and embed it on your website to count the number of visitors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/react */
import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
function App() {
const [websiteUrl, setWebsiteUrl] = useState("");
const [embedCode, setEmbedCode] = useState("");
const [visitorCount, setVisitorCount] = useState(0);
const generateEmbedCode = async () => {
if (!websiteUrl) return;
const response = await fetch("/generate-embed", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ websiteUrl }),
});
if (response.ok) {
const { embedCode, visitorCount } = await response.json();
setEmbedCode(embedCode);
setVisitorCount(visitorCount);
}
};
useEffect(() => {
const fetchVisitorCount = async () => {
if (websiteUrl) {
const response = await fetch(`/visitor-count?url=${encodeURIComponent(websiteUrl)}`);
if (response.ok) {
const { count } = await response.json();
setVisitorCount(count);
}
}
};
fetchVisitorCount();
const interval = setInterval(fetchVisitorCount, 5000);
return () => clearInterval(interval);
}, [websiteUrl]);
return (
<div className="container">
<h1>Website Visitor Counter</h1>
<input
type="text"
value={websiteUrl}
onChange={(e) => setWebsiteUrl(e.target.value)}
placeholder="Enter your website URL"
/>
<button onClick={generateEmbedCode}>Generate Embed Code</button>
{embedCode && (
<div className="result">
<h2>Embed Code (Copy and paste this into your React component):</h2>
<textarea readOnly value={embedCode} />
<p>Current Visitor Count: {visitorCount}</p>
</div>
)}
</div>
);
}
function client() {
createRoot(document.getElementById("root")).render(<App />);
}
if (typeof document !== "undefined") {
client();
}
async function server(request: Request): Promise<Response> {
const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
const SCHEMA_VERSION = 1;
const KEY = new URL(import.meta.url).pathname.split("/").at(-1);
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS ${KEY}_visitor_counts_${SCHEMA_VERSION} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
website_url TEXT UNIQUE NOT NULL,
count INTEGER DEFAULT 0
)
`);
const url = new URL(request.url);
if (url.pathname === "/generate-embed") {
if (request.method === "POST") {
const { websiteUrl } = await request.json();
const encodedUrl = encodeURIComponent(websiteUrl);
const embedCode = `
import { useState, useEffect } from 'react';
function VisitorCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
const fetchCount = async () => {
const response = await fetch('${url.origin}/count-visitor?url=${encodedUrl}');
if (response.ok) {
muhammad_owais_warsi-count_visits.web.val.run
September 21, 2024