Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

BASE_URL setup

Blue Mouse90b59c92158e
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 7fd73cd05..463f93157 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -9,31 +9,12 @@ import {
AuthTokens,
isPersistentSession,
} from '~/utils/session.server'
+import { API_URL } from '~/lib/constants'
// ============================================================================
// MARK: API utils
// ============================================================================
-function getApiUrl(): string {
- const isStaging = process.env.STAGING === 'true'
- const isSelfhosted = Boolean(process.env.__SELFHOSTED)
-
- let apiUrl: string | undefined
-
- if (isSelfhosted || !isStaging) {
- apiUrl = process.env.API_URL
- } else {
- apiUrl = process.env.API_STAGING_URL
- }
-
- if (!apiUrl) {
- throw new Error('API_URL environment variable is not set')
- }
-
- // Ensure trailing slash
- return apiUrl.endsWith('/') ? apiUrl : `${apiUrl}/`
-}
-
export function getClientIP(request: Request): string | null {
const headers = request.headers
@@ -91,9 +72,8 @@ export async function serverFetch<T = unknown>(
skipAuth = false,
} = options
- const apiUrl = getApiUrl()
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
- const url = `${apiUrl}${cleanEndpoint}`
+ const url = `${API_URL}${cleanEndpoint}`
const fetchHeaders: Record<string, string> = {
'Content-Type': 'application/json',
@@ -224,9 +204,8 @@ export async function streamingServerFetch(
skipAuth = false,
} = options
- const apiUrl = getApiUrl()
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
- const url = `${apiUrl}${cleanEndpoint}`
+ const url = `${API_URL}${cleanEndpoint}`
const fetchHeaders: Record<string, string> = {
'Content-Type': 'application/json',
@@ -300,10 +279,8 @@ async function tryRefreshToken(
return { success: false, cookies: [] }
}
- const apiUrl = getApiUrl()
-
try {
- const response = await fetch(`${apiUrl}v1/auth/refresh-token`, {
+ const response = await fetch(`${API_URL}v1/auth/refresh-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index 29391f1a0..0316f4999 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -36,7 +36,7 @@ import {
PuzzleIcon,
PhoneIcon,
} from 'lucide-react'
-import { memo, Fragment, useMemo, useState } from 'react'
+import { memo, Fragment, useMemo, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
@@ -48,6 +48,7 @@ import {
isSelfhosted,
DOCS_URL,
isDisableMarketingPages,
+ API_URL,
} from '~/lib/constants'
import { DashboardBlockReason } from '~/lib/models/User'
import { useAuth } from '~/providers/AuthProvider'
@@ -495,9 +496,33 @@ const DashboardLockedBanner = () => {
)
}
+const SelfhostedCantReachAPIBanner = () => {
+ const { t } = useTranslation('common')
+
+ return (
+ <div className='header-banner w-full bg-amber-500 text-gray-50'>
+ <div className='mx-auto max-w-7xl space-x-2 px-4 py-2 text-center text-sm sm:px-6 lg:px-8'>
+ <span>{t('ce.cantReachBackend')}</span>
+ </div>
+ </div>
+ )
+}
+
const BannerManager = () => {
const { t } = useTranslation('common')
const { user, isAuthenticated } = useAuth()
+ const [showSelfhostedCantReachAPIBanner, setShowSelfhostedCantReachAPIBanner] = useState(false)
+
+ useEffect(() => {
+ const checkApiUrl = async () => {
+ const response = await fetch(`${API_URL}ping`)
+ if (!response.ok) {
+ setShowSelfhostedCantReachAPIBanner(true)
+ }
+ }
+
+ checkApiUrl()
+ }, [])
const [rawStatus, status] = useMemo(() => {
const { trialEndDate } = user || {}
@@ -551,6 +576,10 @@ const BannerManager = () => {
)
}, [status, isAuthenticated, user?.planCode])
+ if (showSelfhostedCantReachAPIBanner) {
+ return <SelfhostedCantReachAPIBanner />
+ }
+
if (!trialBannerHidden) {
return <TrialBanner status={status} rawStatus={rawStatus} />
}
diff --git a/web/app/components/SelfhostedApiUrlBanner.tsx b/web/app/components/SelfhostedApiUrlBanner.tsx
deleted file mode 100644
index 5a02d8a9b..000000000
--- a/web/app/components/SelfhostedApiUrlBanner.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'
-import { memo, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-
-import { isSelfhosted, apiUrlUnprocessed } from '~/lib/constants'
-import Modal from '~/ui/Modal'
-
-const SelfhostedApiUrlBanner = () => {
- const { t } = useTranslation('common')
- const [showMoreInfoModal, setShowMoreInfoModal] = useState(false)
-
- if (!isSelfhosted || apiUrlUnprocessed) {
- return null
- }
-
- return (
- <>
- <div className='bg-yellow-400 dark:bg-yellow-500'>
- <div className='mx-auto max-w-7xl px-3 py-3 sm:px-6 lg:px-8'>
- <div className='flex flex-wrap items-center justify-between'>
- <div className='flex flex-1 items-center'>
- <span className='flex rounded-lg bg-yellow-600 p-2'>
- <ExclamationTriangleIcon
- className='h-6 w-6 text-white'
- aria-hidden='true'
- />
- </span>
- <p className='ml-3 truncate font-medium text-black'>
- {t('ce.noApiUrl.banner')}
- </p>
- </div>
- <div className='order-3 mt-2 w-full shrink-0 sm:order-2 sm:mt-0 sm:w-auto'>
- <span
- onClick={() => setShowMoreInfoModal(true)}
- className='flex cursor-pointer items-center justify-center rounded-md bg-gray-50 px-4 py-2 text-sm font-medium text-yellow-600 hover:bg-yellow-50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- >
- {t('common.learnMore')}
- </span>
- </div>
- </div>
- </div>
- </div>
- <Modal
- onClose={() => setShowMoreInfoModal(false)}
- onSubmit={() => setShowMoreInfoModal(false)}
- submitText={t('common.gotIt')}
- title={t('ce.noApiUrl.title')}
- message={
- <div className='text-left'>
- <p className='mb-3'>{t('ce.noApiUrl.intro1')}</p>
- <p className='mb-3'>{t('ce.noApiUrl.intro2')}</p>
- <ul className='mb-3 list-disc pl-6'>
- <li>{t('ce.noApiUrl.listFe')}</li>
- <li>{t('ce.noApiUrl.listApi')}</li>
- </ul>
- <p className='mb-2 font-medium'>{t('ce.noApiUrl.examplesTitle')}</p>
- <ul className='mb-3 list-disc pl-6'>
- <li>
- {t('ce.noApiUrl.exampleLocal.label')}{' '}
- <code>{t('ce.noApiUrl.exampleLocal.value')}</code>
- </li>
- <li>
- {t('ce.noApiUrl.exampleSubdomain.label')}{' '}
- <code>{t('ce.noApiUrl.exampleSubdomain.value')}</code>
- </li>
- </ul>
- <p>{t('ce.noApiUrl.finalNote')}</p>
- </div>
- }
- type='warning'
- isOpened={showMoreInfoModal}
- />
- </>
- )
-}
-
-export default memo(SelfhostedApiUrlBanner)
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 9dd7aaab8..9734505a0 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -365,6 +365,9 @@ const STAGING_API_URL = isBrowser
const PRODUCTION_API_URL = isBrowser
? window.REMIX_ENV?.API_URL
: process.env.API_URL
+const SELFHOSTED_API_URL = isBrowser
+ ? `${window.REMIX_ENV?.BASE_URL}/backend`
+ : `${process.env.BASE_URL}/backend`
export const COOKIE_DOMAIN =
(isBrowser ? window.REMIX_ENV?.COOKIE_DOMAIN : process.env.COOKIE_DOMAIN) ||
@@ -379,8 +382,7 @@ export const isDisableMarketingPages =
? window.REMIX_ENV?.DISABLE_MARKETING_PAGES
: process.env.DISABLE_MARKETING_PAGES) === 'true'
-export const apiUrlUnprocessed =
- isSelfhosted || !isStaging ? PRODUCTION_API_URL : STAGING_API_URL
+export const apiUrlUnprocessed = isSelfhosted ? SELFHOSTED_API_URL : isStaging ? STAGING_API_URL : PRODUCTION_API_URL
export const TITLE_SUFFIX = isSelfhosted
? '| Swetrix Community Edition'
diff --git a/web/app/root.tsx b/web/app/root.tsx
index adb30336a..a2e7fc120 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -30,7 +30,6 @@ import { ExternalScripts } from 'remix-utils/external-scripts'
import { getAuthenticatedUser } from '~/api/api.server'
import { LocaleLinks } from '~/components/LocaleLinks'
-import SelfhostedApiUrlBanner from '~/components/SelfhostedApiUrlBanner'
import { SEO } from '~/components/SEO'
import {
CONTACT_EMAIL,
@@ -242,6 +241,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
NODE_ENV: process.env.NODE_ENV,
API_URL: process.env.API_URL,
API_STAGING_URL: process.env.API_STAGING_URL,
+ BASE_URL: process.env.BASE_URL,
SELFHOSTED: process.env.__SELFHOSTED,
DISABLE_MARKETING_PAGES: process.env.DISABLE_MARKETING_PAGES,
STAGING: process.env.STAGING,
@@ -283,7 +283,6 @@ const Body = () => {
'bg-slate-900': theme === 'dark',
})}
>
- <SelfhostedApiUrlBanner />
<AuthProvider
initialIsAuthenticated={isAuthed}
initialUser={user}
diff --git a/web/public/locales/de.json b/web/public/locales/de.json
index aa178664e..0903e25a1 100644
--- a/web/public/locales/de.json
+++ b/web/public/locales/de.json
@@ -68,24 +68,7 @@
"failedToLoadUsageInfo": "Fehler beim Laden der Nutzungsinformationen"
},
"ce": {
- "noApiUrl": {
- "banner": "Kann das Backend nicht erreichen — API_URL-Konfiguration prüfen",
- "title": "API_URL ist nicht konfiguriert",
- "intro1": "Sie verwenden die Swetrix Community Edition ohne gesetzte API_URL. Das Frontend kann die API nicht erreichen.",
- "intro2": "Setzen Sie die Umgebungsvariable API_URL auf die URL Ihrer API-Instanz. Beim Self-Hosting gibt es zwei Container:",
- "listFe": "swetrix/swetrix-fe — die Frontend-UI",
- "listApi": "swetrix/swetrix-api — die API (Auth, Datenerfassung)",
- "examplesTitle": "Beispiele",
- "exampleLocal": {
- "label": "Lokaler Standard:",
- "value": "API_URL=http://localhost:8080"
- },
- "exampleSubdomain": {
- "label": "Mit Subdomains:",
- "value": "API_URL=https://swetrix-api.mydomain.com"
- },
- "finalNote": "Bitte konfigurieren Sie dies und starten Sie die Container neu."
- }
+ "cantReachBackend": "Backend nicht erreichbar — stellen Sie sicher, dass BASE_URL auf die URL Ihrer Swetrix-CE-Instanz gesetzt ist"
},
"common": {
"status": "Status",
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 0a3dd1e4e..8343f931e 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -68,24 +68,7 @@
"failedToLoadUsageInfo": "Failed to load usage info"
},
"ce": {
- "noApiUrl": {
- "banner": "Can't reach backend — check API_URL configuration",
- "title": "API_URL is not configured",
- "intro1": "You are running Swetrix Community Edition without API_URL set. The frontend cannot reach the API.",
- "intro2": "Set the API_URL environment variable to your API instance URL. In self-hosting there are two containers:",
- "listFe": "swetrix/swetrix-fe — the frontend UI",
- "listApi": "swetrix/swetrix-api — the API (auth, data ingest)",
- "examplesTitle": "Examples",
- "exampleLocal": {
- "label": "Local default:",
- "value": "API_URL=http://localhost:8080"
- },
- "exampleSubdomain": {
- "label": "With subdomains:",
- "value": "API_URL=https://swetrix-api.mydomain.com"
- },
- "finalNote": "Please configure it and restart the containers."
- }
+ "cantReachBackend": "Can't reach backend — make sure BASE_URL is set to your Swetrix CE instance URL"
},
"common": {
"status": "Status",
diff --git a/web/public/locales/fr.json b/web/public/locales/fr.json
index cdc15bf7e..c76004de7 100644
--- a/web/public/locales/fr.json
+++ b/web/public/locales/fr.json
@@ -68,24 +68,7 @@
"failedToLoadUsageInfo": "Impossible de charger les informations d'utilisation"
},
"ce": {
- "noApiUrl": {
- "banner": "Impossible d’atteindre le backend — vérifiez la configuration d’API_URL",
- "title": "API_URL n’est pas configurée",
- "intro1": "Vous exécutez Swetrix Community Edition sans définir API_URL. Le frontend ne peut pas joindre l’API.",
- "intro2": "Définissez la variable d’environnement API_URL sur l’URL de votre instance d’API. En auto-hébergement, il y a deux conteneurs :",
- "listFe": "swetrix/swetrix-fe — l’interface frontend",
- "listApi": "swetrix/swetrix-api — l’API (authentification, ingestion de données)",
- "examplesTitle": "Exemples",
- "exampleLocal": {
- "label": "Valeur par défaut locale :",
- "value": "API_URL=http://localhost:8080"
- },
- "exampleSubdomain": {
- "label": "Avec des sous-domaines :",
- "value": "API_URL=https://swetrix-api.mydomain.com"
- },
- "finalNote": "Veuillez le configurer et redémarrer les conteneurs."
- }
+ "cantReachBackend": "Impossible de joindre le backend — assurez-vous que BASE_URL est défini sur l’URL de votre instance Swetrix CE"
},
"common": {
"status": "Statut",
diff --git a/web/public/locales/pl.json b/web/public/locales/pl.json
index d3fa6f8fa..b674c319a 100644
--- a/web/public/locales/pl.json
+++ b/web/public/locales/pl.json
@@ -68,24 +68,7 @@
"failedToLoadUsageInfo": "Nie udało się załadować informacji o użyciu"
},
"ce": {
- "noApiUrl": {
- "banner": "Nie można połączyć się z backendem — sprawdź konfigurację API_URL",
- "title": "Nie skonfigurowano API_URL",
- "intro1": "Używasz Swetrix Community Edition bez ustawionej wartości API_URL. Frontend nie może połączyć się z API.",
- "intro2": "Ustaw zmienną środowiskową API_URL na adres URL Twojej instancji API. W przypadku self-hostingu są dwa kontenery:",
- "listFe": "swetrix/swetrix-fe — interfejs frontendu (UI)",
- "listApi": "swetrix/swetrix-api — API (uwierzytelnianie, przyjmowanie danych)",
- "examplesTitle": "Przykłady",
- "exampleLocal": {
- "label": "Domyślnie lokalnie:",
- "value": "API_URL=http://localhost:8080"
- },
- "exampleSubdomain": {
- "label": "Z subdomenami:",
- "value": "API_URL=https://swetrix-api.mydomain.com"
- },
- "finalNote": "Skonfiguruj to i uruchom ponownie kontenery."
- }
+ "cantReachBackend": "Nie można połączyć się z backendem — upewnij się, że BASE_URL jest ustawione na adres URL Twojej instancji Swetrix CE"
},
"common": {
"status": "Status",
diff --git a/web/public/locales/uk.json b/web/public/locales/uk.json
index 9c28084be..b33f4b6f2 100644
--- a/web/public/locales/uk.json
+++ b/web/public/locales/uk.json
@@ -68,24 +68,7 @@
"failedToLoadUsageInfo": "Не вдалося завантажити інформацію про використання"
},
"ce": {
- "noApiUrl": {
- "banner": "Не вдається підключитися до бекенду — перевірте конфігурацію API_URL",
- "title": "API_URL не налаштовано",
- "intro1": "Ви запускаєте Swetrix Community Edition без встановленої API_URL. Фронтенд не може звернутися до API.",
- "intro2": "Встановіть змінну середовища API_URL на URL вашого екземпляра API. При самостійному хостингу є два контейнери:",
- "listFe": "swetrix/swetrix-fe — інтерфейс фронтенду (UI)",
- "listApi": "swetrix/swetrix-api — API (автентифікація, приймання даних)",
- "examplesTitle": "Приклади",
- "exampleLocal": {
- "label": "Типове локальне значення:",
- "value": "API_URL=http://localhost:8080"
- },
- "exampleSubdomain": {
- "label": "З піддоменами:",
- "value": "API_URL=https://swetrix-api.mydomain.com"
- },
- "finalNote": "Будь ласка, налаштуйте це та перезапустіть контейнери."
- }
+ "cantReachBackend": "Не вдається підключитися до бекенду — переконайтеся, що BASE_URL встановлено на URL вашої інсталяції Swetrix CE"
},
"common": {
"status": "Статус",