feat: share shopping lists via a public link

Mirrors the existing recipe public-share pattern (/r/[id], gated by a
visibility flag, no auth required) — shopping lists previously only
supported private per-user collaborator invites (email + viewer/editor
role), with no way to hand someone a link who isn't already a member.

- shoppingLists.isPublic (owner-only toggle, same access-control pattern
  already used for renaming/deleting the list).
- New public /s/[id] route added to PUBLIC_PATHS — read-only aisle-grouped
  view with a signup CTA for logged-out visitors, styled after /r/[id].
- The existing collaborator-invite dialog (ShareShoppingListButton) now
  also has a "Public link" toggle + copy-link button at the top, so
  there's one Share entry point for both private and public sharing.

Verified locally: toggling public via the real dialog UI persists
correctly (confirmed via DB + a fresh curl PATCH to rule out a client
race in my own test script), and the public link loads with zero auth
for a logged-out browser context.
This commit is contained in:
Arnaud
2026-07-12 16:11:57 +02:00
parent e98a9c3bb7
commit a1a11ff5e5
9 changed files with 4875 additions and 4 deletions
@@ -50,7 +50,7 @@ export default async function ShoppingListPage({ params }: Params) {
</div>
<div className="flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
<GroceryExportButton listId={id} instacartEnabled={instacartEnabled} />
{access.role === "owner" && <ShareShoppingListButton listId={id} />}
{access.role === "owner" && <ShareShoppingListButton listId={id} initialIsPublic={list.isPublic} />}
<Link href={`/print/shopping-list/${id}`} target="_blank" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
<Printer className="h-4 w-4" />
{m.common.print}
@@ -26,6 +26,7 @@ export async function GET(_req: NextRequest, { params }: Params) {
const PatchSchema = z.object({
completed: z.boolean().optional(),
name: z.string().min(1).max(100).optional(),
isPublic: z.boolean().optional(),
});
export async function PATCH(req: NextRequest, { params }: Params) {
@@ -45,6 +46,11 @@ export async function PATCH(req: NextRequest, { params }: Params) {
await db.update(shoppingLists).set({ name: body.data.name }).where(eq(shoppingLists.id, id));
}
if (body.data.isPublic !== undefined) {
if (access.role !== "owner") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
await db.update(shoppingLists).set({ isPublic: body.data.isPublic }).where(eq(shoppingLists.id, id));
}
if (body.data.completed) {
if (!canWriteShoppingList(access.role)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
// Mark all items as checked
+99
View File
@@ -0,0 +1,99 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import { Globe } from "lucide-react";
import { auth } from "@/lib/auth/server";
import { db, shoppingLists, eq, and } from "@epicure/db";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getMessages, formatMessage } from "@/lib/i18n/server";
type Params = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Params): Promise<Metadata> {
const { id } = await params;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.isPublic, true)),
});
if (!list) return {};
return { title: list.name };
}
export default async function PublicShoppingListPage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() }).catch(() => null);
const m = getMessages((session?.user as { locale?: string } | undefined)?.locale);
const OTHER = m.mealPlan.aisleOther;
const list = await db.query.shoppingLists.findFirst({
where: and(eq(shoppingLists.id, id), eq(shoppingLists.isPublic, true)),
with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.sortOrder), asc(t.rawName)] } },
});
if (!list) notFound();
const byAisle = list.items.reduce<Record<string, typeof list.items>>((acc, item) => {
const key = item.aisle ?? OTHER;
(acc[key] ??= []).push(item);
return acc;
}, {});
const aisles = Object.keys(byAisle).sort((a, b) => (a === OTHER ? 1 : b === OTHER ? -1 : a.localeCompare(b)));
return (
<div className="container mx-auto max-w-2xl px-4 py-8 space-y-6">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Globe className="h-3.5 w-3.5" />
<span>{m.publicShoppingList.sharedList}</span>
{!session && (
<div className="ml-auto flex items-center gap-2">
<Link href="/signup" className={cn(buttonVariants({ size: "sm" }))}>{m.publicRecipe.signUpFree}</Link>
<Link href="/login" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>{m.publicRecipe.logIn}</Link>
</div>
)}
</div>
<div>
<h1 className="text-3xl font-bold tracking-tight">{list.name}</h1>
<p className="text-muted-foreground mt-1">
{formatMessage(m.shoppingLists.itemsChecked, {
checked: list.items.filter((i) => i.checked).length,
total: list.items.length,
})}
</p>
</div>
{aisles.map((aisle) => (
<div key={aisle} className="space-y-2">
{aisles.length > 1 && (
<h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground border-b pb-1">{aisle}</h2>
)}
<ul className="space-y-1.5">
{byAisle[aisle]!.map((item) => (
<li key={item.id} className="flex items-baseline gap-2 text-sm">
<span
className={cn(
"inline-block h-4 w-4 shrink-0 rounded border translate-y-0.5",
item.checked ? "bg-foreground border-foreground" : "border-input"
)}
/>
<span className="text-muted-foreground tabular-nums min-w-[3.5rem]">
{[item.quantity, item.unit].filter(Boolean).join(" ")}
</span>
<span className={cn(item.checked && "line-through text-muted-foreground")}>{item.rawName}</span>
</li>
))}
</ul>
</div>
))}
{!session && (
<div className="rounded-xl border bg-muted/40 p-6 text-center space-y-3">
<p className="font-semibold">{m.publicShoppingList.wantYourOwn}</p>
<p className="text-sm text-muted-foreground">{m.publicRecipe.wantToSaveDescription}</p>
<Link href="/signup" className={cn(buttonVariants())}>{m.publicRecipe.getStartedFree}</Link>
</div>
)}
</div>
);
}
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
import { UserPlus, X } from "lucide-react";
import { UserPlus, X, Link2, Copy, Check } from "lucide-react";
import { toast } from "sonner";
import {
Dialog,
@@ -13,6 +13,7 @@ import {
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
@@ -21,6 +22,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
type Role = "viewer" | "editor";
@@ -38,9 +40,10 @@ interface Member {
interface Props {
listId: string;
initialIsPublic: boolean;
}
export function ShareShoppingListButton({ listId }: Props) {
export function ShareShoppingListButton({ listId, initialIsPublic }: Props) {
const t = useTranslations("shoppingLists");
const ts = useTranslations("shareDialog");
const tCommon = useTranslations("common");
@@ -50,6 +53,42 @@ export function ShareShoppingListButton({ listId }: Props) {
const [members, setMembers] = useState<Member[]>([]);
const [loading, setLoading] = useState(false);
const [inviting, setInviting] = useState(false);
const [isPublic, setIsPublic] = useState(initialIsPublic);
const [savingPublic, setSavingPublic] = useState(false);
const [copied, setCopied] = useState(false);
async function togglePublic(checked: boolean) {
setSavingPublic(true);
const previous = isPublic;
setIsPublic(checked);
try {
const res = await fetch(`/api/v1/shopping-lists/${listId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isPublic: checked }),
});
if (!res.ok) {
setIsPublic(previous);
toast.error(ts("publicLinkToggleFailed"));
}
} catch {
setIsPublic(previous);
toast.error(ts("publicLinkToggleFailed"));
} finally {
setSavingPublic(false);
}
}
async function copyLink() {
const url = `${window.location.origin}/s/${listId}`;
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
toast.error(ts("copyLinkFailed"));
}
}
async function fetchMembers() {
setLoading(true);
@@ -130,6 +169,25 @@ export function ShareShoppingListButton({ listId }: Props) {
</DialogDescription>
</DialogHeader>
<div className="flex items-center justify-between gap-3 rounded-lg border p-3">
<div className="flex items-center gap-2 min-w-0">
<Link2 className="h-4 w-4 text-muted-foreground shrink-0" />
<div className="min-w-0">
<p className="text-sm font-medium">{ts("publicLinkTitle")}</p>
<p className="text-xs text-muted-foreground">{ts("publicLinkDescription")}</p>
</div>
</div>
<Switch checked={isPublic} disabled={savingPublic} onCheckedChange={(v) => { void togglePublic(v); }} />
</div>
{isPublic && (
<Button type="button" variant="outline" size="sm" className="w-full" onClick={() => void copyLink()}>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
{copied ? ts("linkCopied") : ts("copyLink")}
</Button>
)}
<Separator />
<div className="flex gap-2 mt-2">
<Input
type="email"
+1 -1
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/", "/api/internal/"];
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/s/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/", "/api/internal/"];
const ADMIN_PATHS = ["/admin"];
export async function proxy(request: NextRequest) {
@@ -0,0 +1 @@
ALTER TABLE "shopping_lists" ADD COLUMN "is_public" boolean DEFAULT false NOT NULL;
File diff suppressed because it is too large Load Diff
@@ -225,6 +225,20 @@
"when": 1783841772890,
"tag": "0031_brave_arclight",
"breakpoints": true
},
{
"idx": 32,
"version": "7",
"when": 1783863921901,
"tag": "0032_boring_layla_miller",
"breakpoints": true
},
{
"idx": 33,
"version": "7",
"when": 1783864805460,
"tag": "0033_graceful_jetstream",
"breakpoints": true
}
]
}
+1
View File
@@ -60,6 +60,7 @@ export const shoppingLists = pgTable("shopping_lists", {
id: text("id").primaryKey(),
userId: text("user_id").references(() => users.id, { onDelete: "cascade" }),
name: text("name").notNull(),
isPublic: boolean("is_public").notNull().default(false),
generatedAt: timestamp("generated_at"),
createdAt: timestamp("created_at").notNull().defaultNow(),
});