import { useCallback, useEffect, useMemo, useState } from "react"; import { Link } from "react-router-dom"; import ProxyHostForm from "../components/ProxyHostForm"; import { api, type CurrentUser, type IntegrationProblem, type NpmHost, type NpmOverview } from "../api/client"; import SortableTh from "../components/SortableTh"; import Pagination from "../components/Pagination"; import TableToolbar from "../components/TableToolbar"; import TimeAgo from "../components/TimeAgo"; import EmptyState, { EmptyRow } from "../components/EmptyState"; import { BlockSkeleton } from "../components/Skeleton"; import { ErrorNotice } from "../components/Notice"; import { useSortable } from "../hooks/useSortable"; import { useTableSearch } from "../hooks/useTableSearch"; import { usePagination } from "../hooks/usePagination"; import { downloadCsv } from "../utils/csv"; import { confirmDialog, promptDialog } from "../utils/dialogs"; import { formatDate } from "../utils/date"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; import PageIntro from "../components/PageIntro"; type Row = NpmHost & { integrationId: number; canManage: boolean; integrationName: string; domain: string; target: string; certDays: number | null; certName: string; statusRank: number; serverName: string }; const DAY_MS = 86_400_000; const daysLeft = (iso: string | null): number | null => (iso && Number.isFinite(Date.parse(iso)) ? Math.floor((Date.parse(iso) - Date.now()) / DAY_MS) : null); function StatusBadge({ h }: { h: Row }) { if (!h.enabled) return Switched off; if (!h.online) return ( Not working ); return Working; } function CertBadge({ h }: { h: Row }) { if (!h.certificate) return {h.sslForced ? "—" : "No certificate"}; const d = h.certDays; const color = d === null ? "secondary" : d < 0 ? "red" : d <= 3 ? "red" : d <= 14 ? "yellow" : "green"; const words = d === null ? "no end date" : d < 0 ? `ran out ${-d} ${d === -1 ? "day" : "days"} ago` : d === 0 ? "ends today" : `${d} ${d === 1 ? "day" : "days"} left`; return ( {words}
{h.certificate.name}
); } /** * What Nginx Proxy Manager proxies: each name people use, where it forwards to (and which server that is), its certificate and whether NPM could set it up. Read * from NPM when the page is opened (and at most once a minute); nothing here changes anything in NPM. */ export default function ProxyHosts({ user }: { user: CurrentUser }) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [reading, setReading] = useState(false); const load = useCallback( (refresh = false) => api.npm .overview(refresh) .then((res) => { setData(res); setError(null); }) .catch((err) => setError(readableError(err))), [], ); useEffect(() => { void load(); const timer = setInterval(() => void load(), 60_000); return () => clearInterval(timer); }, [load]); async function readNow() { setReading(true); await load(true); setReading(false); toast.success("Read from Nginx Proxy Manager."); } const rows: Row[] = useMemo( () => (data?.integrations ?? []).flatMap((i) => i.hosts.map((h) => ({ ...h, integrationId: i.id, canManage: i.canManage, integrationName: i.name, domain: h.domains.join(", "), target: `${h.forwardScheme}://${h.forwardHost}${h.forwardPort !== null ? `:${h.forwardPort}` : ""}`, certDays: daysLeft(h.certificate?.expiresAt ?? null), certName: h.certificate?.name ?? "", statusRank: !h.enabled ? 2 : h.online ? 1 : 0, serverName: h.server?.name ?? "", })), ), [data], ); const isAdmin = user.role === "admin"; const managing = (data?.integrations ?? []).filter((i) => i.canManage && !i.error); const canManageAny = isAdmin && (data?.integrations ?? []).some((i) => i.canManage); // The form that is open: a new host (on one of the NPMs that can be managed) or a change of one. const [form, setForm] = useState<{ mode: "new"; integrationId: number } | { mode: "edit"; row: Row } | null>(null); async function afterChange(message: string) { setForm(null); toast.success(message); await load(true); } async function switchHost(h: Row) { if (h.enabled && !(await confirmDialog({ title: "Switch off proxy host", message: `Switch off ${h.domains[0]}? Nginx Proxy Manager stops serving ${h.domains.length > 1 ? "its names" : "it"}. Nothing is lost, and switching it on again brings it back.`, confirmLabel: "Switch off", danger: true }))) return; try { await api.npm.setHostEnabled(h.integrationId, h.id, !h.enabled); toast.success(`${h.domains[0]} is ${h.enabled ? "off" : "on"}.`); await load(true); } catch (err) { toast.error(readableError(err)); } } async function deleteHost(h: Row) { const typed = await promptDialog({ title: "Delete proxy host", message: `This deletes the proxy host ${h.domains.join(", ")} (it forwards to ${h.target}) in ${h.integrationName}: Nginx Proxy Manager stops serving ${h.domains.length > 1 ? "those names" : "that name"}. Type its first name to confirm.`, label: "First name", confirmLabel: "Delete", required: true, }); if (typed === null) return; if (typed.trim().toLowerCase() !== h.domains[0]) { toast.error("That is not the first name of the host, so nothing was deleted."); return; } try { await api.npm.deleteHost(h.integrationId, h.id, h.domains[0]); toast.success(`Deleted ${h.domains[0]}.`); await load(true); } catch (err) { toast.error(readableError(err)); } } const tableSearch = useTableSearch(rows); const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "statusRank", "asc", { url: true }); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); const problems: (IntegrationProblem & { integration: string })[] = (data?.integrations ?? []).flatMap((i) => i.problems.map((p) => ({ ...p, integration: i.name }))); const soon = rows.filter((h) => h.enabled && h.certDays !== null && h.certDays <= 14).length; const noNpm = data !== null && data.integrations.length === 0; function exportCsv() { downloadCsv( "proxy-hosts.csv", ["Names", "Forwards to", "Server", "Status", "Certificate", "Certificate ends", "Force HTTPS", "Nginx Proxy Manager"], (sorted ?? []).map((h) => [h.domain, h.target, h.serverName, !h.enabled ? "switched off" : h.online ? "working" : "not working", h.certName, h.certificate?.expiresAt ?? "", h.sslForced ? "yes" : "no", h.integrationName]), ); } return ( <>

Proxy hosts

{(user.role === "admin" || user.role === "operator") && data && data.integrations.length > 0 && (
{isAdmin && managing.length > 0 && ( )}
)}
What Nginx Proxy Manager serves: the name, where it forwards to, the certificate and whether NPM could set it up. {canManageAny ? "An administrator can also make, change, switch off and delete hosts here. " : "It only reads — nothing here changes anything in NPM. "}A certificate in its last two weeks, or a host NPM can’t set up, is an alert. {isAdmin && data && data.integrations.length > 0 && !canManageAny && (
To make and change proxy hosts from here, give the Nginx Proxy Manager integration a user with Manage on Proxy Hosts: Integrations → edit → Email of a user that may manage.
)} {form && form.mode === "new" && ( <> {managing.length > 1 && (
)} i.id === form.integrationId)?.name ?? ""} certificates={managing.find((i) => i.id === form.integrationId)?.certificates ?? []} onDone={(name) => void afterChange(`Made the proxy host ${name}.`)} onCancel={() => setForm(null)} /> )} {form && form.mode === "edit" && ( i.id === form.row.integrationId)?.certificates ?? []} host={form.row} onDone={(name) => void afterChange(`Saved ${name}.`)} onCancel={() => setForm(null)} /> )} {data === null && !error && } {noNpm && (
)} {data && data.integrations.length > 0 && (
{data.integrations.map((i) => (
{i.name} {i.error ? <> — couldn’t be read: {i.error} : <> — read {i.version ? ` · version ${i.version}` : ""} · {i.hosts.length} {i.hosts.length === 1 ? "host" : "hosts"}}
))}
)} {data && data.integrations.some((i) => !i.error) && ( <>
{[ { label: "Proxy hosts", value: rows.length, color: "" }, { label: "Not working", value: rows.filter((h) => h.enabled && !h.online).length, color: rows.some((h) => h.enabled && !h.online) ? "text-red" : "text-green" }, { label: "Certificates ending within 14 days", value: soon, color: soon > 0 ? "text-yellow" : "text-green" }, { label: "Switched off", value: rows.filter((h) => !h.enabled).length, color: "" }, ].map((c) => (
{c.value}
{c.label}
))}
{problems.length > 0 && (

Needs attention

{problems.map((p) => (
{p.severity === "critical" ? "Critical" : "Warning"} {p.message}
))}
)}
label="Status" sortKeyName="statusRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Name" sortKeyName="domain" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Forwards to" sortKeyName="target" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Certificate" sortKeyName="certDays" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {canManageAny && {(pageItems ?? []).length === 0 && tableSearch.setQuery("") : undefined} />} {(pageItems ?? []).map((h) => ( {canManageAny && ( )} ))}
}
{h.error && h.enabled &&
{h.error.slice(0, 120)}
}
{h.domains.map((d, i) => ( ))} {data && data.integrations.length > 1 &&
{h.integrationName}
}
{h.target} {h.server && (
{h.server.name}
)}
{h.canManage && ( <> )}
)} ); }