Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Add caddy (#90)

Bill Yangd10017686f5d
diff --git a/Caddyfile b/Caddyfile
new file mode 100644
index 000000000..bc7a5f886
--- /dev/null
+++ b/Caddyfile
@@ -0,0 +1,24 @@
+# Caddyfile
+# Use the domain name passed from docker-compose environment
+{$DOMAIN_NAME} {
+ # Enable compression
+ encode zstd gzip
+
+ # Proxy API requests to the backend service
+ handle_path /api/* {
+ reverse_proxy backend:3001
+ }
+
+ # Proxy all other requests to the client service
+ handle {
+ reverse_proxy client:3002
+ }
+
+ # Optional: Add security headers (example)
+ # header {
+ # Strict-Transport-Security max-age=31536000;
+ # X-Content-Type-Options nosniff
+ # X-Frame-Options DENY
+ # Referrer-Policy strict-origin-when-cross-origin
+ # }
+}
\ No newline at end of file
diff --git a/client/Dockerfile b/client/Dockerfile
index 49ff948b1..e666336a0 100644
--- a/client/Dockerfile
+++ b/client/Dockerfile
@@ -17,7 +17,6 @@ COPY . .
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
-# Uncomment the following line in case you want to disable telemetry during the build.
ENV NEXT_TELEMETRY_DISABLED 1
ARG NEXT_PUBLIC_BACKEND_URL
ENV NEXT_PUBLIC_BACKEND_URL=${NEXT_PUBLIC_BACKEND_URL}
diff --git a/client/src/app/login/page.tsx b/client/src/app/login/page.tsx
index 282131906..66c98ed3c 100644
--- a/client/src/app/login/page.tsx
+++ b/client/src/app/login/page.tsx
@@ -147,14 +147,12 @@ export default function Page() {
</Alert>
)}
- {IS_CLOUD && (
- <div className="text-center text-sm">
- Don't have an account?{" "}
- <Link href="/signup" className="underline">
- Sign up
- </Link>
- </div>
- )}
+ <div className="text-center text-sm">
+ Don't have an account?{" "}
+ <Link href="/signup" className="underline">
+ Sign up
+ </Link>
+ </div>
</div>
</form>
</CardContent>
diff --git a/docker-compose.yml b/docker-compose.yml
index 07ea8f665..03a91327b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,6 +1,24 @@
-version: '3.8'
-
services:
+ caddy:
+ image: caddy:latest
+ container_name: caddy
+ restart: unless-stopped
+ ports:
+ - "80:80"
+ - "443:443"
+ - "443:443/udp" # Needed for HTTP/3
+ volumes:
+ - ./Caddyfile:/etc/caddy/Caddyfile # Mount Caddy config file
+ - caddy_data:/data # Mount persistent data volume for certs etc.
+ - caddy_config:/config # Mount persistent config volume
+ environment:
+ # Pass domain name for use in Caddyfile
+ # Email is configured via Caddyfile global options
+ - DOMAIN_NAME=${DOMAIN_NAME}
+ depends_on:
+ - backend
+ - client
+
clickhouse:
container_name: clickhouse
image: clickhouse/clickhouse-server:latest
@@ -19,6 +37,7 @@ services:
timeout: 5s
retries: 5
start_period: 10s
+ restart: unless-stopped
postgres:
image: postgres:latest
@@ -27,18 +46,15 @@ services:
POSTGRES_USER: frog
POSTGRES_PASSWORD: frog
POSTGRES_DB: analytics
- ports:
- - "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
+ restart: unless-stopped
backend:
container_name: backend
build:
context: ./server
dockerfile: Dockerfile
- ports:
- - "3001:3001"
environment:
- NODE_ENV=production
- CLICKHOUSE_HOST=http://clickhouse:8123
@@ -59,6 +75,7 @@ services:
condition: service_healthy
postgres:
condition: service_started
+ restart: unless-stopped
client:
container_name: client
@@ -67,15 +84,16 @@ services:
dockerfile: Dockerfile
args:
NEXT_PUBLIC_BACKEND_URL: ${BASE_URL}
- ports:
- - "3002:3002"
environment:
- NODE_ENV=production
- NEXT_PUBLIC_BACKEND_URL=${BASE_URL}
- CLOUD=${CLOUD}
depends_on:
- backend
+ restart: unless-stopped
volumes:
clickhouse-data:
postgres-data:
+ caddy_data: # Persistent volume for Caddy's certificates and state
+ caddy_config: # Persistent volume for Caddy's configuration cache (optional but good practice)
diff --git a/docs/src/content/self-hosting.mdx b/docs/src/content/self-hosting.mdx
index 754119ea3..0b05b48ba 100644
--- a/docs/src/content/self-hosting.mdx
+++ b/docs/src/content/self-hosting.mdx
@@ -1,105 +1,68 @@
import { Steps } from 'nextra/components'
+import { Callout } from 'nextra/components'
-# Self Hosting
+# Self Hosting Frogstats
-You can self-host Frogstats by following the steps below.
+This guide will walk you through setting up your own instance of Frogstats.
+## Prerequisites
-## Create manually
+Before you begin, ensure you have the following:
-Nextra works like a Next.js plugin, and it accepts a theme config (layout) to
-render the page. To start: [^3]
+- **A Linux VPS:** We use [Hetzner Cloud](https://hetzner.cloud/?ref=QEdVqVpTLBDP) for everything (referral link - but Hetzner is legitimately the best value). CX11 for ~$4/month will be fine for small-medium sized projects.
+- **A Domain Name:** You'll need a domain or subdomain (e.g., `tracking.yourdomain.com`) pointed to your VPS's IP address. HTTPS is required because browsers block tracking scripts served over insecure HTTP.
+- **Docker Engine:** Docker is used to run the application stack. Installation instructions are in Step 1.
+- **Git:** Needed to clone the repository.
-<Steps>
-### Install Next.js, Nextra and React [^1]
+<Callout type="info">
+ This guide has been tested on Ubuntu 24 LTS. While it should work on other distributions, your mileage may vary.
+</Callout>
-{/* ```sh npm2yarn
-npm i react react-dom next nextra
-``` */}
+## Setup Steps
-### Install the docs theme [^2]
+<Steps>
+### 1. Install Docker and Git
-```sh npm2yarn
-npm i nextra-theme-docs
-```
+First, connect to your VPS via SSH.
-### Create the following Next.js config and theme config under the root directory
+**Install Docker Engine:** Follow the official instructions for your Linux distribution:
+[https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/)
-```js filename="next.config.mjs"
-import nextra from 'nextra'
+Make sure to complete the [post-installation steps for Linux](https://docs.docker.com/engine/install/linux-postinstall/) as well, particularly adding your user to the `docker` group so you don't have to use `sudo` for every Docker command.
-const withNextra = nextra({
- theme: 'nextra-theme-blog',
- themeConfig: './theme.config.js'
-})
-export default withNextra()
+**Install Git:** If Git is not already installed, install it using your distribution's package manager. For Debian/Ubuntu:
+```bash
+sudo apt update && sudo apt install -y git
```
-### Create a `theme.config.js` file for the docs theme
-
-```js filename="theme.config.js"
-export default {
- project: {
- link: 'https://github.com/shuding/nextra' // GitHub link in the navbar
- },
- docsRepositoryBase: 'https://github.com/shuding/nextra/blob/master', // base URL for the docs repository
- getNextSeoProps: () => ({ titleTemplate: '%s – Nextra' }),
- navigation: true,
- darkMode: true,
- footer: {
- text: `MIT ${new Date().getFullYear()} © Shu Ding.`
- },
- editLink: {
- text: 'Edit this page on GitHub'
- },
- logo: (
- <>
- <svg>...</svg>
- <span>Next.js Static Site Generator</span>
- </>
- ),
- head: (
- <>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="description" content="Nextra: the next docs builder" />
- <meta name="og:title" content="Nextra: the next docs builder" />
- </>
- ),
- primaryHue: {
- dark: 204,
- light: 212
- }
-}
+### 2. Clone the Frogstats Repository
+
+Clone the project repository from GitHub:
+```bash
+git clone https://github.com/goldflag/frogstats.git
+cd frogstats
```
-> [!NOTE]
->
-> More configuration options for the docs theme can be found
-> [here](/themes/docs/configuration).
+### 3. Run the Setup Script
-### You are good to go! Run `next dev` to start
+The repository includes a setup script that configures the necessary environment variables (including generating a secure secret) and starts the application using Docker Compose.
-</Steps>
+Run the script, replacing `your.domain.name` with the domain or subdomain you configured in the prerequisites:
+```bash
+chmod +x setup.sh
+./setup.sh your.domain.name
+```
----
+The script will create a `.env` file and then build and start the containers. This might take a few minutes the first time.
-<span id="sidebar-and-anchor-links" />
+### 4. Sign Up
-> [!NOTE]
->
-> Any `.md` or `.mdx` file will turn into a doc page and be displayed in
-> sidebar. You can also create a `_meta.js` file to customize the page order and
-> title. <br /> Check the source code: https://github.com/shuding/nextra for
-> more information.
+Once the services are running, Caddy (the webserver) will automatically obtain an SSL certificate for your domain.
-> [!TIP]
->
-> You can also use
-> [`<style jsx>`](https://nextjs.org/docs/basic-features/built-in-css-support#css-in-js)
-> to style elements inside `theme.config.js`.
+Open your browser and navigate to `https://your.domain.name/signup` (using the domain you provided to the setup script).
-[^1]: Install Next.js, Nextra and React.
+Create your admin account. You can then log in and start adding your websites!
-[^2]: Install the docs theme.
+</Steps>
-[^3]: To start.
+Congratulations! You have successfully self-hosted Frogstats.
diff --git a/server/docker-entrypoint.sh b/server/docker-entrypoint.sh
index cd1ecff51..9655eed53 100644
--- a/server/docker-entrypoint.sh
+++ b/server/docker-entrypoint.sh
@@ -1,9 +1,6 @@
#!/bin/sh
set -e
-# Docker Compose already ensures services are ready using healthchecks
-# and dependency conditions in the docker-compose.yml file
-
# Run migrations explicitly using the npm script
echo "Running database migrations...."
npm run db:push
diff --git a/server/src/api/sites/getSites.ts b/server/src/api/sites/getSites.ts
index ebeb369f3..660b28d6a 100644
--- a/server/src/api/sites/getSites.ts
+++ b/server/src/api/sites/getSites.ts
@@ -4,6 +4,7 @@ import { db } from "../../db/postgres/postgres.js";
import { member } from "../../db/postgres/schema.js";
import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";
import { getSubscriptionInner } from "../stripe/getSubscription.js";
+import { IS_CLOUD } from "../../lib/const.js";
// Default event limit for users without an active subscription
const DEFAULT_EVENT_LIMIT = 10_000;
@@ -13,12 +14,20 @@ export async function getSites(req: FastifyRequest, reply: FastifyReply) {
// Get sites the user has access to
const sitesData = await getSitesUserHasAccessTo(req);
- // Enhance sites data - removing usage limit information for now
const enhancedSitesData = await Promise.all(
sitesData.map(async (site) => {
let isOwner = false;
let ownerId = "";
+ if (!IS_CLOUD) {
+ return {
+ ...site,
+ monthlyEventCount: 0,
+ eventLimit: Infinity,
+ overMonthlyLimit: false,
+ isOwner: true,
+ };
+ }
// Determine ownership if organization ID exists
if (site.organizationId) {
const orgOwnerResult = await db
diff --git a/server/src/api/stripe/createCheckoutSession.ts b/server/src/api/stripe/createCheckoutSession.ts
index 0182b616c..abec249fa 100644
--- a/server/src/api/stripe/createCheckoutSession.ts
+++ b/server/src/api/stripe/createCheckoutSession.ts
@@ -1,8 +1,9 @@
-import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
-import { stripe } from "../../lib/stripe.js";
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import Stripe from "stripe";
import { db } from "../../db/postgres/postgres.js";
import { user as userSchema } from "../../db/postgres/schema.js";
-import { eq } from "drizzle-orm";
+import { stripe } from "../../lib/stripe.js";
interface CheckoutRequestBody {
priceId: string;
@@ -49,7 +50,7 @@ export async function createCheckoutSession(
// 2. If the user doesn't have a Stripe Customer ID, create one
if (!stripeCustomerId) {
- const customer = await stripe.customers.create({
+ const customer = await (stripe as Stripe).customers.create({
email: user.email,
metadata: {
userId: user.id, // Link Stripe customer to your internal user ID
@@ -65,7 +66,7 @@ export async function createCheckoutSession(
}
// 4. Create a Stripe Checkout Session
- const session = await stripe.checkout.sessions.create({
+ const session = await (stripe as Stripe).checkout.sessions.create({
payment_method_types: ["card"],
mode: "subscription",
customer: stripeCustomerId,
diff --git a/server/src/api/stripe/createPortalSession.ts b/server/src/api/stripe/createPortalSession.ts
index bafc7f696..5305c4aaf 100644
--- a/server/src/api/stripe/createPortalSession.ts
+++ b/server/src/api/stripe/createPortalSession.ts
@@ -3,6 +3,7 @@ import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
import { user as userSchema } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
+import Stripe from "stripe";
interface PortalRequestBody {
returnUrl: string;
@@ -44,7 +45,9 @@ export async function createPortalSession(
}
// 2. Create a Stripe Billing Portal Session
- const portalSession = await stripe.billingPortal.sessions.create({
+ const portalSession = await (
+ stripe as Stripe
+ ).billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: returnUrl, // The user will be redirected here after managing their billing
});
diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.ts
index db678a8b8..e9cc5d0ec 100644
--- a/server/src/api/stripe/getSubscription.ts
+++ b/server/src/api/stripe/getSubscription.ts
@@ -34,7 +34,7 @@ export async function getSubscriptionInner(userId: string) {
}
// 2. List active subscriptions for the customer from Stripe
- const subscriptions = await stripe.subscriptions.list({
+ const subscriptions = await (stripe as Stripe).subscriptions.list({
customer: user.stripeCustomerId,
status: "active", // Only fetch active subscriptions
limit: 1, // Users should only have one active subscription in this model
diff --git a/server/src/api/stripe/webhook.ts b/server/src/api/stripe/webhook.ts
index 053b66387..eaef351e7 100644
--- a/server/src/api/stripe/webhook.ts
+++ b/server/src/api/stripe/webhook.ts
@@ -29,7 +29,7 @@ export async function handleWebhook(
return reply.status(400).send("Webhook error: No raw body available");
}
- event = stripe.webhooks.constructEvent(
+ event = (stripe as Stripe).webhooks.constructEvent(
rawBody,
sig as string,
webhookSecret
diff --git a/server/src/cron/monthly-usage-checker.ts b/server/src/cron/monthly-usage-checker.ts
index 202b8528c..c1e4173d4 100644
--- a/server/src/cron/monthly-usage-checker.ts
+++ b/server/src/cron/monthly-usage-checker.ts
@@ -5,6 +5,7 @@ import { eq, inArray, and } from "drizzle-orm";
import { db } from "../db/postgres/postgres.js";
import { processResults } from "../api/analytics/utils.js";
import { stripe } from "../lib/stripe.js";
+import Stripe from "stripe";
// Default event limit for users without an active subscription
const DEFAULT_EVENT_LIMIT = 10_000;
@@ -69,7 +70,7 @@ async function getUserSubscriptionInfo(userData: {
try {
// Fetch active subscriptions for the customer from Stripe
- const subscriptions = await stripe.subscriptions.list({
+ const subscriptions = await (stripe as Stripe).subscriptions.list({
customer: userData.stripeCustomerId,
status: "active",
limit: 1,
diff --git a/server/src/lib/stripe.ts b/server/src/lib/stripe.ts
index afdb90e7b..dcadd36f4 100644
--- a/server/src/lib/stripe.ts
+++ b/server/src/lib/stripe.ts
@@ -5,13 +5,8 @@ dotenv.config();
const secretKey = process.env.STRIPE_SECRET_KEY;
-if (!secretKey) {
- throw new Error(
- "Stripe secret key is not defined in environment variables. Please set STRIPE_SECRET_KEY."
- );
-}
-
-export const stripe = new Stripe(secretKey, {
- // apiVersion: "2024-06-20", // Use the latest API version - Removed to use SDK default
- typescript: true, // Enable TypeScript support
-});
+export const stripe = secretKey
+ ? new Stripe(secretKey, {
+ typescript: true, // Enable TypeScript support
+ })
+ : null;
diff --git a/setup.sh b/setup.sh
new file mode 100644
index 000000000..e855cf1c3
--- /dev/null
+++ b/setup.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+
+# Exit immediately if a command exits with a non-zero status.
+set -e
+
+# Check if domain name argument is provided
+if [ -z "$1" ]; then
+ echo "Usage: $0 <domain_name>"
+ echo "Example: $0 myapp.example.com"
+ exit 1
+fi
+
+DOMAIN_NAME="$1"
+BASE_URL="https://${DOMAIN_NAME}"
+
+# Generate a secure random secret for BETTER_AUTH_SECRET
+# Uses OpenSSL if available, otherwise falls back to /dev/urandom
+if command -v openssl &> /dev/null; then
+ BETTER_AUTH_SECRET=$(openssl rand -hex 32)
+elif [ -e /dev/urandom ]; then
+ BETTER_AUTH_SECRET=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 32)
+else
+ echo "Error: Could not generate secure secret. Please install openssl or ensure /dev/urandom is available." >&2
+ exit 1
+fi
+
+# Create or overwrite the .env file
+echo "Creating .env file..."
+cat > .env << EOL
+# Variables configured by setup.sh
+DOMAIN_NAME=${DOMAIN_NAME}
+BASE_URL=${BASE_URL}
+BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET}
+
+# Defaulting to empty strings to suppress docker-compose warnings
+STRIPE_SECRET_KEY=
+STRIPE_WEBHOOK_SECRET=
+CLOUD=
+EOL
+
+echo ".env file created successfully with domain ${DOMAIN_NAME}."
+
+# Build and start the Docker Compose stack
+echo "Building and starting Docker services..."
+docker compose up --build -d
+
+echo "Setup complete. Services are starting in the background."
+echo "You can monitor logs with: docker compose logs -f"
\ No newline at end of file