diff --git a/.env.example b/.env.example index be28962..3049dcf 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,7 @@ NEXT_PUBLIC_SUPABASE_URL=https://xsnmteskpdguamrofsfx.supabase.co NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your_supabase_publishable_key +# Optional fallback for projects still using the legacy anon key. +NEXT_PUBLIC_SUPABASE_ANON_KEY= # Server-only secret. Never prefix this with NEXT_PUBLIC_ or expose it to the browser. SUPABASE_SECRET_KEY= AI_PROVIDER= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5e871b2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: PHANTOM quality checks + +on: + pull_request: + branches: [main] + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: phantom-ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + validate: + name: Typecheck and production build + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Check out source + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Install dependencies + run: npm install + + - name: TypeScript validation + run: npm run typecheck + + - name: Production build + run: npm run build diff --git a/README.md b/README.md index 63cb1bd..8dff1c7 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,85 @@ # PHANTOM -### The internet never really dies. +### A little less feed. A lot more signal. -PHANTOM is a modern resurrection of Bulletin Board Systems (BBS): a community-first digital space with terminal-inspired rooms, live conversations, and a shared knowledge archive. +**PHANTOM resurrects the spirit of Bulletin Board Systems for the modern web.** It is a community-first network built around intentional rooms, live conversations, and a shared knowledge archive—not an endless algorithmic feed. -## What works in the current core build +## Try PHANTOM -- Public room directory backed by Supabase -- Email magic-link sign-in foundation and auth-aware UI -- Authenticated join/leave for public rooms -- Persistent room messages with Supabase Realtime updates -- Public knowledge archive: publish, browse, and search entries -- Content report intake for messages and archive entries -- Responsive terminal-inspired dashboard +- **Interactive demo:** https://phantom-gkn8.onrender.com/demo +- **Main application:** https://phantom-gkn8.onrender.com +- **Source code:** https://github.com/devshieldhq/phantom -**Still in progress:** moderator review/removal tools, server-enforced rate limits, offline archive and draft sync, AI summaries, multiplayer game, and full end-to-end QA. +The demo is open to everyone. No account or setup is needed. Explore sample rooms, send local demo messages, search the knowledge archive, and discover the network. Demo activity is temporary, runs entirely in the browser, and resets when you leave. -## Stack +The main application is the live Supabase-backed experience. Sign-in is required for joining rooms, posting persistent messages, publishing archive entries, and reporting content. -- Next.js App Router + TypeScript -- Tailwind CSS + Lucide +## Product experience + +- **Community rooms:** public spaces for introductions, building, discovery, and conversation. +- **Live transmissions:** persistent room messages with Supabase Realtime updates. +- **Knowledge archive:** publish, browse, and search public entries worth preserving. +- **Community safety:** report messages and archive entries for moderation review. +- **Open entry:** try the interactive demo without creating an account. +- **Responsive interface:** a terminal-inspired workspace designed for desktop and mobile. + +## Built with + +- Next.js App Router, React, and TypeScript +- Tailwind CSS and Lucide icons - Supabase Auth, Postgres, Row Level Security, and Realtime -- Render web service +- Render + +## Local development -## Local setup +1. Install Node.js 20 or newer. +2. Clone this repository and install dependencies: + + ```bash + npm install + ``` -1. Install Node.js 20+. -2. Run `npm install`. 3. Copy `.env.example` to `.env.local`. -4. Set the Supabase project URL and publishable key: - - `NEXT_PUBLIC_SUPABASE_URL` - - `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` -5. Run `npm run dev`. +4. Configure the public Supabase project values: + + ```env + NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url + NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your_publishable_key + # Optional legacy fallback when the publishable key is not set: + NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key + ``` + +5. Start the development server: -Apply the SQL migrations in `supabase/migrations` to a fresh Supabase project in order. Configure the Supabase Auth email provider and add your local/deployed callback URLs to the allowed redirect URLs. + ```bash + npm run dev + ``` -## Security principles +The interactive demo at `/demo` runs independently of Supabase configuration. The main application requires a configured Supabase project for its persistent features. -- Enforce authorization with Supabase RLS, not UI checks alone. +Apply the SQL migrations in `supabase/migrations` to a fresh Supabase project in order. Configure the Supabase Auth email provider and add local and deployed callback URLs to the allowed redirect URLs. + +## Security + +- Authorization is enforced through Supabase Row Level Security, not UI checks alone. - Never expose service-role or secret keys in browser code. +- `SUPABASE_SECRET_KEY` is server-only. +- The public publishable key is preferred; the anon key is supported as a fallback. - Public rooms and public archive entries are readable without signing in. - Joining rooms, posting messages, publishing archive entries, and submitting reports require authentication. -- Users can only view their own report submissions. - Keep private content out of public caches and offline storage. -## Build plan +## Current development status + +The interactive demo is available without authentication. The main application includes the room directory, authentication foundation, room membership, persistent messages, realtime updates, public archive, and report intake. + +Further work includes moderator review and removal tools, server-enforced rate limits, offline archive and draft sync, AI-assisted summaries, multiplayer experiences, and full end-to-end QA. + +## Competition build notes + +PHANTOM is a modern resurrection of the Bulletin Board System: a place where people intentionally gather, exchange knowledge, and preserve useful information. The project keeps the social intimacy of early online communities while using a modern web stack. -See [project tasks](.kiro/specs/phantom-platform/tasks.md) for current implementation status and remaining work. +See `.kiro/specs/phantom-platform` for product requirements and implementation notes. -## Deployment +## License -PHANTOM is deployed on Render: https://phantom-gkn8.onrender.com +MIT. See [LICENSE](LICENSE). diff --git a/app/demo/page.tsx b/app/demo/page.tsx new file mode 100644 index 0000000..990abf6 --- /dev/null +++ b/app/demo/page.tsx @@ -0,0 +1,153 @@ +"use client"; + +import { useMemo, useState, type FormEvent } from "react"; +import Link from "next/link"; +import { + Activity, Archive, ArrowLeft, ArrowUpRight, BookOpen, Check, + ChevronRight, Command, Compass, Hash, MessageSquare, Radio, + Search, Send, Shield, Sparkles, Terminal, Users, Wifi +} from "lucide-react"; + +type DemoMessage = { id: number; room: string; author: string; time: string; body: string; self?: boolean }; +type DemoEntry = { id: number; title: string; category: string; excerpt: string; date: string }; + +const initialMessages: DemoMessage[] = [ + { id: 1, room: "the-lobby", author: "moth.exe", time: "09:41", body: "The old internet had something special. You arrived because you were curious." }, + { id: 2, room: "the-lobby", author: "signal_ghost", time: "09:43", body: "No algorithm deciding what I should see. Just people building things." }, + { id: 3, room: "the-lobby", author: "you", time: "09:44", body: "That is exactly the energy we are bringing back.", self: true }, + { id: 4, room: "build-lab", author: "patchwork", time: "10:02", body: "Today's tiny win: shipped a useful tool with zero tracking pixels." }, + { id: 5, room: "build-lab", author: "moth.exe", time: "10:05", body: "Small, intentional software is a kind of rebellion." }, + { id: 6, room: "lost-and-found", author: "archive_angel", time: "08:17", body: "Found an old public-domain field manual. Added it to the archive." } +]; + +const rooms = [ + { id: "the-lobby", name: "The Lobby", slug: "the-lobby", description: "Introductions, ideas, and unexpected connections.", members: 128, icon: "◉" }, + { id: "build-lab", name: "Build Lab", slug: "build-lab", description: "Work in progress. Share what you're making.", members: 64, icon: "⌘" }, + { id: "lost-and-found", name: "Lost & Found", slug: "lost-and-found", description: "Rescue forgotten knowledge and useful links.", members: 42, icon: "⌁" }, + { id: "after-hours", name: "After Hours", slug: "after-hours", description: "Slow conversations for curious minds.", members: 31, icon: "☾" } +]; + +const entries: DemoEntry[] = [ + { id: 1, title: "The small-web field guide", category: "FIELD NOTES", excerpt: "A practical starting point for making a corner of the internet that feels human again.", date: "NOV 28, 2026" }, + { id: 2, title: "A checklist for owning your data", category: "PRIVACY", excerpt: "Simple habits for keeping your digital life portable, private, and under your control.", date: "NOV 24, 2026" }, + { id: 3, title: "BBS culture: a short history", category: "HISTORY", excerpt: "Before feeds and infinite scroll, communities gathered one dial-up connection at a time.", date: "NOV 19, 2026" } +]; + +export default function DemoPage() { + const [activeRoom, setActiveRoom] = useState("the-lobby"); + const [tab, setTab] = useState<"rooms" | "archive" | "network">("rooms"); + const [messages, setMessages] = useState(initialMessages); + const [draft, setDraft] = useState(""); + const [joined, setJoined] = useState(["the-lobby"]); + const [search, setSearch] = useState(""); + const [showGuide, setShowGuide] = useState(true); + const [copied, setCopied] = useState(false); + + const currentRoom = rooms.find((room) => room.id === activeRoom) ?? rooms[0]; + const roomMessages = messages.filter((message) => message.room === activeRoom); + const filteredEntries = useMemo(() => entries.filter((entry) => + (entry.title + " " + entry.excerpt + " " + entry.category).toLowerCase().includes(search.toLowerCase()) + ), [search]); + + function sendMessage(event: FormEvent) { + event.preventDefault(); + const body = draft.trim(); + if (!body) return; + if (!joined.includes(activeRoom)) { + setJoined((current) => [...current, activeRoom]); + } + setMessages((current) => [...current, { + id: Date.now(), room: activeRoom, author: "you", time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), body, self: true + }]); + setDraft(""); + } + + function copyInvite() { + if (typeof navigator !== "undefined" && navigator.clipboard) { + void navigator.clipboard.writeText("PHANTOM — The internet never really dies. https://phantom-gkn8.onrender.com/demo"); + setCopied(true); + window.setTimeout(() => setCopied(false), 1800); + } + } + + return ( +
+
+
+
+
+
+ + + PHANTOM_THE INTERNET NEVER REALLY DIES + +
INTERACTIVE DEMO
+ BACK TO PHANTOM +
+
+ +
+
+
+
SYSTEM PREVIEW / 001
+

A little less feed.
A lot more signal.

+

Step inside a living, community-owned corner of the internet. Explore rooms, send a transmission, and discover knowledge worth keeping.

+
+
+
+
GUEST SESSION
No account · No setup
+
+
+ {showGuide &&
+

YOUR 60-SECOND FIELD TEST

Pick a room → send a message → search the archive → explore the network.

+ +
} +
+ +
+
+
+
PHANTOM://COMMUNITY-NETWORK
+
SIMULATED LIVE ENVIRONMENT
+
+
+ + +
+ {tab === "rooms" &&
+
COMMUNITY{currentRoom.slug.toUpperCase()}

{currentRoom.name}

{currentRoom.description}

+
+
TRANSMISSIONS / {roomMessages.length.toString().padStart(2, "0")} ENCRYPTED CHANNEL PREVIEW
+
+ {roomMessages.length ? roomMessages.map((message) =>
{message.author.slice(0, 2).toUpperCase()}
{message.author}{message.self && YOU}{message.time}

{message.body}

) :
This channel is quiet. Start the signal.
} +
+
QUICK TRANSMISSIONLOCAL DEMO
> setDraft(event.target.value)} maxLength={240} placeholder="Say something worth remembering..." className="min-w-0 flex-1 bg-transparent text-xs text-[#e1ebe3] outline-none placeholder:text-[#53665a]"/>
+
+
} + + {tab === "archive" &&
THE KNOWLEDGE VAULT

Keep the good stuff.

A community memory that outlives the scroll. Search the demo archive and open a field note.

setSearch(event.target.value)} placeholder="Search knowledge..." className="w-full bg-transparent py-3.5 text-xs outline-none placeholder:text-[#53665a]"/>
{filteredEntries.map((entry) =>
{entry.category}{entry.date}

{entry.title}

{entry.excerpt}

OPEN FIELD NOTE
)}{filteredEntries.length === 0 &&

No entries match that search. Try another signal.

}
} + + {tab === "network" &&
NETWORK TOPOLOGY

Small rooms. Real connections.

Explore the channels that make up this little corner of the internet. No feed to beat. No algorithm to please.

{rooms.map((room, index) => )}
COMMUNITY-POWERED

265

DEMO MEMBERS

{messages.length.toString().padStart(2, "0")}

TRANSMISSIONS

OPEN

COMMUNITY ACCESS

} +
+
+
SESSION ACTIVE / YOUR CHANGES ARE LOCAL
+
+

This is an interactive preview with sample content. Messages and membership changes are temporary and reset when you leave. The main PHANTOM app connects to its live Supabase backend.

+
+ +
PHANTOM NETWORK / RESURRECT THE SMALL WEBENTER THE MAIN NETWORK
+
+
+ ); +} diff --git a/app/globals.css b/app/globals.css index 53ff02e..a911185 100644 --- a/app/globals.css +++ b/app/globals.css @@ -10,3 +10,6 @@ a { color: inherit; text-decoration: none; } button { cursor: pointer; } .terminal-grid { background-image: linear-gradient(rgba(156,255,107,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(156,255,107,.035) 1px, transparent 1px); background-size: 32px 32px; } .glow { text-shadow: 0 0 22px rgba(156,255,107,.38); } + +:focus-visible { outline: 2px solid #9cff6b; outline-offset: 3px; } +button:disabled { cursor: not-allowed; } diff --git a/app/layout.tsx b/app/layout.tsx index b4058f0..dadfff7 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -3,8 +3,8 @@ import { Geist_Mono } from "next/font/google"; import "./globals.css"; const mono = Geist_Mono({ subsets: ["latin"], variable: "--font-geist-mono" }); export const metadata: Metadata = { - title: "PHANTOM — The internet never really dies.", - description: "A modern resurrection of Bulletin Board Systems. Find your room. Keep the signal alive." + title: "PHANTOM — A little less feed. A lot more signal.", + description: "A living network inspired by the original Bulletin Board Systems. Explore community rooms, live conversations, and a knowledge archive. Try the interactive demo." }; export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { return {children}; diff --git a/app/login/page.tsx b/app/login/page.tsx index 438522f..638b15f 100644 --- a/app/login/page.tsx +++ b/app/login/page.tsx @@ -1,39 +1,61 @@ "use client"; + import { FormEvent, useState } from "react"; import Link from "next/link"; +import { ArrowLeft, ArrowUpRight, CheckCircle2, Terminal, Wifi } from "lucide-react"; import { createClient } from "@/lib/supabase/client"; export default function LoginPage() { const [email, setEmail] = useState(""); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(""); - async function submit(e: FormEvent) { - e.preventDefault(); - setBusy(true); setMessage(""); + const [sent, setSent] = useState(false); + + async function submit(event: FormEvent) { + event.preventDefault(); + setBusy(true); + setMessage(""); + setSent(false); try { const supabase = createClient(); const { error } = await supabase.auth.signInWithOtp({ - email, + email: email.trim(), options: { emailRedirectTo: `${window.location.origin}/auth/callback` } }); if (error) throw error; - setMessage("Check your inbox for your secure sign-in link."); - } catch (err) { - setMessage(err instanceof Error ? err.message : "Unable to send sign-in link."); - } finally { setBusy(false); } + setSent(true); + setMessage("Your sign-in link is on its way. Check your inbox to reconnect."); + } catch (error) { + setMessage(error instanceof Error ? error.message : "Unable to send a sign-in link. Please try again."); + } finally { + setBusy(false); + } } - return
-
- ← PHANTOM -

IDENTITY // AUTHENTICATION

-

Reconnect to the network.

-

Enter your email. We'll send you a secure sign-in link.

-
- - setEmail(e.target.value)} placeholder="you@example.com" className="w-full border border-[#24352e] bg-[#090d0c] px-4 py-3 text-sm outline-none focus:border-[#9cff6b]"/> - -
- {message &&

{message}

} -
-
; -} \ No newline at end of file + + return ( +
+
+
+ PHANTOM NETWORK +
+
IDENTITY / SECURE ACCESS
+

Your signal is waiting.

+

Reconnect to your rooms, conversations, and the knowledge you've helped preserve. We'll send a secure sign-in link to your inbox.

+ +
+ + setEmail(event.target.value)} placeholder="you@example.com" className="w-full border border-[#2b4032] bg-[#080d0b] px-4 py-4 text-sm text-[#e5eee7] outline-none transition placeholder:text-[#53665a] focus:border-[#9cff6b]"/> + +
+ + {message &&
{sent && }{message}
} + +
+

Just looking around?

+ EXPLORE THE INTERACTIVE DEMO +

PHANTOM will never ask for your password. Your secure access link is sent directly to your email.

+
+
+
+ ); +} diff --git a/app/page.tsx b/app/page.tsx index 16c557a..6bcab83 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { FormEvent, useCallback, useEffect, useMemo, useState } from "react"; +import { FormEvent, useCallback, useEffect, useState } from "react"; import { Activity, Archive, ArrowUpRight, Hash, LogOut, MessageSquare, Radio, Search, Send, ShieldAlert, Terminal, Users, Wifi, X } from "lucide-react"; import { createClient } from "@/lib/supabase/client"; @@ -13,7 +13,7 @@ type Tab = "rooms" | "archive" | "network"; const stamp = (value: string) => new Date(value).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); export default function Home() { - const supabase = useMemo(() => createClient(), []); + const [supabase, setSupabase] = useState | null>(null); const [user, setUser] = useState<{ id: string; email?: string } | null>(null); const [profile, setProfile] = useState(null); const [rooms, setRooms] = useState([]); @@ -33,10 +33,20 @@ export default function Home() { const [loading, setLoading] = useState(true); const [notice, setNotice] = useState(""); + useEffect(() => { + try { + setSupabase(createClient()); + } catch { + setNotice("Supabase is not configured. Add the public project URL and publishable or anon key to .env.local."); + setLoading(false); + } + }, []); + const activeRoom = rooms.find((room) => room.id === active) ?? rooms[0] ?? null; const joinedCount = memberships.length; const loadMessages = useCallback(async (roomId: string) => { + if (!supabase) return; const { data, error } = await supabase.from("messages") .select("id, room_id, user_id, body, created_at") .eq("room_id", roomId).order("created_at", { ascending: true }).limit(100); @@ -53,6 +63,7 @@ export default function Home() { }, [supabase]); const loadArchive = useCallback(async () => { + if (!supabase) return; const { data, error } = await supabase.from("archive_entries") .select("id, title, body, summary, author_id, created_at") .eq("is_public", true).order("created_at", { ascending: false }).limit(100); @@ -61,6 +72,7 @@ export default function Home() { }, [supabase]); const loadCore = useCallback(async () => { + if (!supabase) return; setLoading(true); const [{ data: authData }, roomResult] = await Promise.all([ supabase.auth.getUser(), @@ -89,13 +101,14 @@ export default function Home() { }, [active, loadArchive, supabase]); useEffect(() => { + if (!supabase) return; void loadCore(); const { data: listener } = supabase.auth.onAuthStateChange(() => { void loadCore(); }); return () => listener.subscription.unsubscribe(); }, [loadCore, supabase]); useEffect(() => { - if (!activeRoom) return; + if (!supabase || !activeRoom) return; void loadMessages(activeRoom.id); const channel = supabase.channel(`room-${activeRoom.id}`) .on("postgres_changes", { event: "INSERT", schema: "public", table: "messages", filter: `room_id=eq.${activeRoom.id}` }, () => { @@ -105,6 +118,7 @@ export default function Home() { }, [activeRoom?.id, loadMessages, supabase]); async function joinRoom() { + if (!supabase) { setNotice("Supabase is not configured. Add the public project URL and key first."); return; } if (!user || !activeRoom) { window.location.href = "/login"; return; } setBusy(true); setNotice(""); const { error } = await supabase.from("room_members").insert({ room_id: activeRoom.id, user_id: user.id }); @@ -117,6 +131,7 @@ export default function Home() { } async function leaveRoom() { + if (!supabase) { setNotice("Supabase is not configured. Add the public project URL and key first."); return; } if (!user || !activeRoom) return; setBusy(true); setNotice(""); const { error } = await supabase.from("room_members").delete().eq("room_id", activeRoom.id).eq("user_id", user.id); @@ -130,6 +145,7 @@ export default function Home() { async function sendMessage(event: FormEvent) { event.preventDefault(); + if (!supabase) { setNotice("Supabase is not configured. Add the public project URL and key first."); return; } if (!user) { window.location.href = "/login"; return; } if (!activeRoom || !memberships.includes(activeRoom.id) || !draft.trim()) return; setBusy(true); setNotice(""); @@ -142,6 +158,7 @@ export default function Home() { async function publishArchive(event: FormEvent) { event.preventDefault(); + if (!supabase) { setNotice("Supabase is not configured. Add the public project URL and key first."); return; } if (!user) { window.location.href = "/login"; return; } if (archiveTitle.trim().length < 3 || !archiveBody.trim()) return; setBusy(true); setNotice(""); @@ -159,6 +176,7 @@ export default function Home() { async function submitReport(event: FormEvent) { event.preventDefault(); + if (!supabase) { setNotice("Supabase is not configured. Add the public project URL and key first."); return; } if (!user || !reportTarget) return; setBusy(true); setNotice(""); const payload = { @@ -175,6 +193,7 @@ export default function Home() { } async function signOut() { + if (!supabase) return; setBusy(true); await supabase.auth.signOut(); setUser(null); setProfile(null); setMemberships([]); @@ -191,15 +210,20 @@ export default function Home() {
PHANTOM_
THE INTERNET NEVER REALLY DIES
-
DATABASE CONNECTED / PUBLIC NETWORK
+
{supabase ? "DATABASE CONNECTED" : "DATABASE CONFIG REQUIRED"} / PUBLIC NETWORK
{user ?
{profile?.display_name || profile?.username || user.email}
: CONNECT}
-
+
-
SYSTEM // 001

Some things should
never go offline.

A living network for curious minds. Find your people, exchange ideas, and leave something worth finding.

-
NETWORK STATUS
{loading ? "..." : "LIVE"}connected to Supabase
{String(rooms.length).padStart(2,"0")}
ROOMS
{joinedCount.toString().padStart(2,"0")}
JOINED
{archive.length.toString().padStart(2,"0")}
ARCHIVE
+
SYSTEM // 001

Some things should
never go offline.

A living network for curious minds. Find your people, exchange ideas, and leave something worth finding.

+ +

NO ACCOUNT NEEDED TO TRY THE DEMO

+
NETWORK STATUS
{loading ? "..." : supabase ? "LIVE" : "OFFLINE"}{supabase ? "connected to Supabase" : "configuration required"}
{String(rooms.length).padStart(2,"0")}
ROOMS
{joinedCount.toString().padStart(2,"0")}
JOINED
{archive.length.toString().padStart(2,"0")}
ARCHIVE
{notice &&
{notice}
} diff --git a/lib/supabase/client.ts b/lib/supabase/client.ts index f8d5653..4383fb6 100644 --- a/lib/supabase/client.ts +++ b/lib/supabase/client.ts @@ -2,7 +2,7 @@ import { createBrowserClient } from "@supabase/ssr"; export function createClient() { const url = process.env.NEXT_PUBLIC_SUPABASE_URL; - const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY; + const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; if (!url || !key) throw new Error("Supabase environment variables are missing."); return createBrowserClient(url, key); } diff --git a/lib/supabase/server.ts b/lib/supabase/server.ts index 5121124..c28b520 100644 --- a/lib/supabase/server.ts +++ b/lib/supabase/server.ts @@ -4,7 +4,7 @@ import { cookies } from "next/headers"; export async function createClient() { const cookieStore = await cookies(); const url = process.env.NEXT_PUBLIC_SUPABASE_URL; - const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY; + const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; if (!url || !key) throw new Error("Supabase environment variables are missing."); return createServerClient(url, key, { cookies: { diff --git a/middleware.ts b/middleware.ts new file mode 100644 index 0000000..6699adc --- /dev/null +++ b/middleware.ts @@ -0,0 +1,38 @@ +import { createServerClient, type CookieOptions } from "@supabase/ssr"; +import { NextResponse, type NextRequest } from "next/server"; + +export async function middleware(request: NextRequest) { + let supabaseResponse = NextResponse.next({ request }); + + const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; + const supabaseKey = + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; + + // Allow static builds and local previews without Supabase configuration. + if (!supabaseUrl || !supabaseKey) { + return supabaseResponse; + } + + const supabase = createServerClient(supabaseUrl, supabaseKey, { + cookies: { + getAll() { + return request.cookies.getAll(); + }, + setAll(cookiesToSet: Array<{ name: string; value: string; options?: CookieOptions }>) { + cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value)); + supabaseResponse = NextResponse.next({ request }); + cookiesToSet.forEach(({ name, value, options }) => + supabaseResponse.cookies.set(name, value, options) + ); + }, + }, + }); + + await supabase.auth.getClaims(); + return supabaseResponse; +} + +export const config = { + matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"], +};