feat(pwa): add Serwist service worker, manifest, icons, install prompt

- Wrap next.config.ts with @serwist/next (webpack mode, disabled in dev)
- Service worker: NetworkOnly for /api/*, offline fallback → /~offline
- Web app manifest via Next.js metadata API (app/manifest.ts)
- PNG icon set generated with sharp (192, 512, maskable-512, apple-180)
- iOS meta tags: appleWebApp, themeColor viewport export
- Middleware: pwaAssets early-return so /sw.js never gets a 302→login
- Offline fallback page at /~offline (static, no auth dependency)
- InstallPrompt component: beforeinstallprompt (Android) + iOS Share sheet instructions
- Logout (menu/page.tsx): purge all SW caches on signout (shared-device safety)
- Fix invite/[token]/page.tsx params type for Next.js 16 (use(params))
- Build script: next build --webpack (Serwist requires webpack, not Turbopack)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Manohar Gupta 2026-05-27 23:20:48 +05:30
parent 942a03d99a
commit b6814579c6
21 changed files with 1069 additions and 3841 deletions

View file

@ -1,4 +1,12 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
import withSerwistInit from "@serwist/next";
const withSerwist = withSerwistInit({
swSrc: "src/app/sw.ts",
swDest: "public/sw.js",
// Disable in dev so it never interferes with HMR / hot reload
disable: process.env.NODE_ENV === "development",
});
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
output: "standalone", output: "standalone",
@ -26,4 +34,4 @@ const nextConfig: NextConfig = {
}, },
}; };
export default nextConfig; export default withSerwist(nextConfig);

View file

@ -4,19 +4,22 @@
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build --webpack",
"start": "next start", "start": "next start",
"db:generate": "drizzle-kit generate", "db:generate": "drizzle-kit generate",
"db:migrate": "tsx src/db/migrate.ts", "db:migrate": "tsx src/db/migrate.ts",
"db:studio": "drizzle-kit studio", "db:studio": "drizzle-kit studio",
"db:pull": "drizzle-kit pull", "db:pull": "drizzle-kit pull",
"db:build-migrator": "node scripts/build-migrator.mjs" "db:build-migrator": "node scripts/build-migrator.mjs",
"test": "vitest run",
"test:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"@auth/drizzle-adapter": "^1.11.2", "@auth/drizzle-adapter": "^1.11.2",
"@aws-sdk/client-s3": "^3.1045.0", "@aws-sdk/client-s3": "^3.1045.0",
"@aws-sdk/s3-request-presigner": "^3.1045.0", "@aws-sdk/s3-request-presigner": "^3.1045.0",
"@react-pdf/renderer": "^4.5.1", "@react-pdf/renderer": "^4.5.1",
"@serwist/next": "9.5.11",
"arctic": "^3.7.0", "arctic": "^3.7.0",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"chart.js": "^4.5.1", "chart.js": "^4.5.1",
@ -26,7 +29,6 @@
"nanoid": "^5.1.11", "nanoid": "^5.1.11",
"next": "16.2.6", "next": "16.2.6",
"next-auth": "5.0.0-beta.31", "next-auth": "5.0.0-beta.31",
"next-pwa": "^5.6.0",
"nodemailer": "^7.0.13", "nodemailer": "^7.0.13",
"openai": "^6.37.0", "openai": "^6.37.0",
"postgres": "^3.4.9", "postgres": "^3.4.9",
@ -36,6 +38,7 @@
"react-dom": "19.2.4", "react-dom": "19.2.4",
"recharts": "^3.8.1", "recharts": "^3.8.1",
"resend": "^6.12.3", "resend": "^6.12.3",
"serwist": "9.5.11",
"sharp": "^0.34.5", "sharp": "^0.34.5",
"zod": "^4.4.3" "zod": "^4.4.3"
}, },
@ -46,10 +49,12 @@
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/sharp": "^0.32.0", "@types/sharp": "^0.32.0",
"@vitest/coverage-v8": "^4.1.7",
"drizzle-kit": "^0.31.10", "drizzle-kit": "^0.31.10",
"esbuild": "^0.25.12", "esbuild": "^0.25.12",
"tailwindcss": "^4", "tailwindcss": "^4",
"tsx": "^4.21.0", "tsx": "^4.21.0",
"typescript": "^5" "typescript": "^5",
"vitest": "^4.1.7"
} }
} }

4513
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

BIN
public/icons/192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

BIN
public/icons/512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

BIN
public/icons/apple-180.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View file

@ -1,21 +0,0 @@
{
"name": "Tia - Baby Tracking",
"short_name": "Tia",
"description": "Your baby tracking companion",
"start_url": "/",
"display": "standalone",
"background_color": "#fdf2f2",
"theme_color": "#fb7185",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,47 @@
// Generates PWA icon PNGs from an SVG template using sharp.
// Run: node scripts/generate-icons.mjs
import sharp from "sharp";
import { writeFileSync } from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const outDir = path.join(__dirname, "../public/icons");
// Brand colors from the app
const BG = "#fb7185"; // rose-400
// SVG template — rounded square with cherry blossom character.
// For maskable: full bleed background, content within safe zone (inner 80%).
function makeSvg(size, maskable = false) {
const radius = maskable ? 0 : Math.round(size * 0.18);
const fontSize = maskable ? Math.round(size * 0.48) : Math.round(size * 0.56);
const y = maskable ? Math.round(size * 0.68) : Math.round(size * 0.72);
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
<rect width="${size}" height="${size}" rx="${radius}" fill="${BG}"/>
<text
x="${size / 2}"
y="${y}"
font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
font-weight="700"
font-size="${fontSize}"
text-anchor="middle"
fill="white"
dominant-baseline="auto"
>T</text>
</svg>`;
}
const icons = [
{ name: "192.png", size: 192, maskable: false },
{ name: "512.png", size: 512, maskable: false },
{ name: "maskable-512.png", size: 512, maskable: true },
{ name: "apple-180.png", size: 180, maskable: false },
];
for (const icon of icons) {
const svg = Buffer.from(makeSvg(icon.size, icon.maskable));
const outPath = path.join(outDir, icon.name);
await sharp(svg).png().toFile(outPath);
console.log(`${icon.name}`);
}

View file

@ -2,6 +2,7 @@ import { ThemeProvider } from "@/app/ThemeProvider";
import { FamilyProvider } from "@/app/FamilyProvider"; import { FamilyProvider } from "@/app/FamilyProvider";
import { PageTransition } from "@/components/PageTransition"; import { PageTransition } from "@/components/PageTransition";
import { BottomNav } from "@/components/BottomNav"; import { BottomNav } from "@/components/BottomNav";
import { InstallPrompt } from "@/components/InstallPrompt";
export default function AppLayout({ export default function AppLayout({
children, children,
@ -13,6 +14,7 @@ export default function AppLayout({
<FamilyProvider> <FamilyProvider>
<PageTransition>{children}</PageTransition> <PageTransition>{children}</PageTransition>
<BottomNav /> <BottomNav />
<InstallPrompt />
</FamilyProvider> </FamilyProvider>
</ThemeProvider> </ThemeProvider>
); );

View file

@ -25,6 +25,12 @@ export default function MenuPage() {
setSigningOut(true); setSigningOut(true);
try { try {
await fetch("/api/auth/signout", { method: "POST" }); await fetch("/api/auth/signout", { method: "POST" });
// Purge SW caches so a shared device can't see the previous user's
// cached baby photos or shell state after login.
if ("caches" in window) {
const keys = await caches.keys();
await Promise.all(keys.map((k) => caches.delete(k)));
}
router.push("/login"); router.push("/login");
} catch (err) { } catch (err) {
console.error("Sign out failed:", err); console.error("Sign out failed:", err);

BIN
src/app/apple-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View file

@ -1,9 +1,10 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
export default function InvitePage({ params }: { params: { token: string } }) { export default function InvitePage({ params }: { params: Promise<{ token: string }> }) {
const { token } = use(params);
const router = useRouter(); const router = useRouter();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(""); const [error, setError] = useState("");
@ -18,7 +19,7 @@ export default function InvitePage({ params }: { params: { token: string } }) {
const res = await fetch("/api/invites/accept", { const res = await fetch("/api/invites/accept", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: params.token, userId }), body: JSON.stringify({ token, userId }),
}); });
const data = await res.json(); const data = await res.json();
@ -36,7 +37,7 @@ export default function InvitePage({ params }: { params: { token: string } }) {
} }
checkInvite(); checkInvite();
}, [params.token, router]); }, [token, router]);
if (loading) { if (loading) {
return ( return (

View file

@ -1,4 +1,4 @@
import type { Metadata } from "next"; import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono, Caveat } from "next/font/google"; import { Geist, Geist_Mono, Caveat } from "next/font/google";
import "./globals.css"; import "./globals.css";
@ -18,13 +18,21 @@ const caveat = Caveat({
}); });
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Tia - Baby Tracking", title: "Tia — Baby Tracker",
description: "Your baby tracking companion", description: "Track feeds, sleep, milestones and memories.",
manifest: "/manifest.json",
icons: { icons: {
icon: "/icon.svg", icon: "/icon.svg",
apple: "/icon.svg", apple: "/apple-icon.png",
}, },
appleWebApp: {
capable: true,
statusBarStyle: "default",
title: "Tia",
},
};
export const viewport: Viewport = {
themeColor: "#fb7185",
}; };
export default function RootLayout({ export default function RootLayout({

23
src/app/manifest.ts Normal file
View file

@ -0,0 +1,23 @@
import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
name: "Tia — Baby Tracker",
short_name: "Tia",
description: "Track feeds, sleep, milestones and memories.",
start_url: "/?source=pwa",
display: "standalone",
background_color: "#fdf2f2",
theme_color: "#fb7185",
icons: [
{ src: "/icons/192.png", sizes: "192x192", type: "image/png" },
{ src: "/icons/512.png", sizes: "512x512", type: "image/png" },
{
src: "/icons/maskable-512.png",
sizes: "512x512",
type: "image/png",
purpose: "maskable",
},
],
};
}

42
src/app/sw.ts Normal file
View file

@ -0,0 +1,42 @@
import { defaultCache } from "@serwist/next/worker";
import type { PrecacheEntry, RuntimeCaching, SerwistGlobalConfig } from "serwist";
import { NetworkOnly, Serwist } from "serwist";
declare global {
interface WorkerGlobalScope extends SerwistGlobalConfig {
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
}
}
declare const self: ServiceWorkerGlobalScope;
// SECURITY: API responses carry session-protected personal/medical data.
// They must NEVER be cached. NetworkOnly = always hit the server, no cache.
// Listed first so it wins over defaultCache.
const runtimeCaching: RuntimeCaching[] = [
{
matcher: ({ sameOrigin, url }) =>
sameOrigin && url.pathname.startsWith("/api/"),
handler: new NetworkOnly(),
},
...defaultCache,
];
const serwist = new Serwist({
precacheEntries: self.__SW_MANIFEST,
precacheOptions: { cleanupOutdatedCaches: true },
skipWaiting: true,
clientsClaim: true,
navigationPreload: true,
disableDevLogs: true,
runtimeCaching,
fallbacks: {
entries: [
{
url: "/~offline",
matcher: ({ request }) => request.mode === "navigate",
},
],
},
});
serwist.addEventListeners();

19
src/app/~offline/page.tsx Normal file
View file

@ -0,0 +1,19 @@
"use client";
export default function OfflinePage() {
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-rose-50 to-amber-50 p-8 text-center">
<div className="text-6xl mb-6">🌸</div>
<h1 className="text-2xl font-bold text-rose-500 mb-3">You&apos;re offline</h1>
<p className="text-gray-600 mb-6 max-w-xs">
Reconnect to the internet to keep tracking with Tia.
</p>
<button
onClick={() => window.location.reload()}
className="px-6 py-3 bg-rose-400 text-white rounded-xl font-semibold active:opacity-80"
>
Try again
</button>
</div>
);
}

View file

@ -0,0 +1,115 @@
"use client";
import { useEffect, useState } from "react";
// Extend the BeforeInstallPromptEvent type (not in standard lib)
interface BeforeInstallPromptEvent extends Event {
prompt(): Promise<void>;
readonly userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
}
function IOSInstallInstructions({ onDismiss }: { onDismiss: () => void }) {
return (
<div className="fixed bottom-4 left-4 right-4 z-50 bg-white border border-rose-100 rounded-2xl shadow-lg p-4">
<div className="flex justify-between items-start mb-2">
<div className="flex items-center gap-2">
<span className="text-2xl">🌸</span>
<span className="font-semibold text-gray-900">Install Tia</span>
</div>
<button
onClick={onDismiss}
className="text-gray-400 text-xl leading-none p-1"
aria-label="Dismiss"
>
</button>
</div>
<p className="text-sm text-gray-600 mb-2">
Add Tia to your home screen for the best experience.
</p>
<div className="flex items-center gap-2 text-sm text-gray-700">
<span>Tap</span>
<span className="inline-flex items-center justify-center w-7 h-7 bg-gray-100 rounded-md text-base"></span>
<span>then</span>
<span className="font-medium">"Add to Home Screen"</span>
</div>
</div>
);
}
const DISMISSED_KEY = "tia_install_prompt_dismissed";
export function InstallPrompt() {
const [deferred, setDeferred] = useState<BeforeInstallPromptEvent | null>(null);
const [isIOS, setIsIOS] = useState(false);
const [dismissed, setDismissed] = useState(true); // start hidden to avoid flash
useEffect(() => {
if (typeof window === "undefined") return;
const alreadyDismissed = localStorage.getItem(DISMISSED_KEY) === "1";
if (alreadyDismissed) return;
const standalone = window.matchMedia("(display-mode: standalone)").matches;
if (standalone) return; // already installed
// iOS Safari: no beforeinstallprompt, needs manual instructions
const ios = /iphone|ipad|ipod/i.test(navigator.userAgent);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if (ios && isSafari) {
setIsIOS(true);
setDismissed(false);
}
// Android / Chrome: capture the deferred install event
const handler = (e: Event) => {
e.preventDefault();
setDeferred(e as BeforeInstallPromptEvent);
setDismissed(false);
};
window.addEventListener("beforeinstallprompt", handler);
return () => window.removeEventListener("beforeinstallprompt", handler);
}, []);
const handleDismiss = () => {
setDismissed(true);
localStorage.setItem(DISMISSED_KEY, "1");
};
const handleInstall = async () => {
if (!deferred) return;
await deferred.prompt();
const { outcome } = await deferred.userChoice;
if (outcome === "accepted") {
setDeferred(null);
setDismissed(true);
}
};
if (dismissed) return null;
if (deferred) {
return (
<div className="fixed bottom-4 left-4 right-4 z-50 bg-white border border-rose-100 rounded-2xl shadow-lg p-4 flex items-center gap-3">
<span className="text-2xl">🌸</span>
<div className="flex-1">
<p className="font-semibold text-gray-900 text-sm">Install Tia</p>
<p className="text-xs text-gray-500">Add to home screen for quick access</p>
</div>
<button onClick={handleDismiss} className="text-gray-400 p-1 text-lg" aria-label="Dismiss"></button>
<button
onClick={handleInstall}
className="px-4 py-2 bg-rose-400 text-white rounded-xl text-sm font-semibold"
>
Install
</button>
</div>
);
}
if (isIOS) {
return <IOSInstallInstructions onDismiss={handleDismiss} />;
}
return null;
}

View file

@ -1,6 +1,18 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import type { NextRequest } from "next/server"; import type { NextRequest } from "next/server";
// PWA static assets — must bypass auth entirely.
// If the SW or manifest gets a 302→login, the browser registers the login
// page as the service worker, which breaks auth for the entire PWA session.
const pwaAssets = [
"/sw.js",
"/sw.js.map",
"/manifest.webmanifest",
"/~offline",
"/icons/",
"/serwist-",
];
// Public routes that don't require authentication // Public routes that don't require authentication
const publicRoutes = [ const publicRoutes = [
"/", "/",
@ -41,6 +53,13 @@ const protectedApiRoutes = [
export function middleware(request: NextRequest) { export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl; const { pathname } = request.nextUrl;
// Always pass PWA assets through — never redirect to login
for (const asset of pwaAssets) {
if (pathname === asset || pathname.startsWith(asset)) {
return NextResponse.next();
}
}
// Always allow public routes // Always allow public routes
for (const route of publicRoutes) { for (const route of publicRoutes) {
if (pathname === route || pathname.startsWith(route + "/")) { if (pathname === route || pathname.startsWith(route + "/")) {

View file

@ -30,5 +30,5 @@
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts",
"**/*.mts" "**/*.mts"
], ],
"exclude": ["node_modules"] "exclude": ["node_modules", "src/app/sw.ts"]
} }