6. Backend filesThe backend, ready to paste
Starting files for Claude Code. Test each one before you launch.
supabase/schema.sql · Run once in Supabase: SQL Editor, New query, paste, Run. One table, no personal data.
-- Stores only what is needed to send one daily reminder.
create table if not exists public.push_subs (
endpoint text primary key,
p256dh text not null,
auth text not null,
remind_hour smallint not null check (remind_hour between 0 and 23),
tz text not null,
last_sent date,
created_at timestamptz not null default now()
);
-- Row level security on with no policies:
-- the public anon key cannot read or write this table.
-- Only the /api functions, using the service role key, can reach it.
alter table public.push_subs enable row level security;
create index if not exists push_subs_hour_idx on public.push_subs (remind_hour);
api/unlock.js · Checks the access code from the access card. ACCESS_CODES can hold several codes separated by commas, so you can change the code without breaking old buyers.
import { timingSafeEqual } from 'node:crypto';
function same(a, b) {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
}
export default function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const raw = req.body && typeof req.body.code === 'string' ? req.body.code : '';
const code = raw.trim().toUpperCase();
if (code.length < 4 || code.length > 64 || !/^[A-Z0-9-]+$/.test(code)) {
return res.status(400).json({ error: 'Enter the access code from your access card.' });
}
const valid = (process.env.ACCESS_CODES || '')
.split(',')
.map((c) => c.trim().toUpperCase())
.filter(Boolean);
if (valid.length === 0) {
return res.status(500).json({ error: 'Server not configured' });
}
if (!valid.some((c) => same(c, code))) {
return res.status(401).json({ error: 'That code does not match. Check your access card.' });
}
return res.status(200).json({ ok: true });
}api/vapid-public-key.js · Gives the app the public push key. The public key is safe to share. The private key stays in Vercel.
export default function handler(req, res) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' });
}
const key = process.env.VAPID_PUBLIC_KEY;
if (!key || key.length > 200) {
return res.status(500).json({ error: 'Server not configured' });
}
res.setHeader('Cache-Control', 'public, max-age=3600');
return res.status(200).json({ key });
}api/subscribe.js · Saves or updates one phone's reminder. Validates the push address, keys, hour and time zone.
import { createClient } from '@supabase/supabase-js';
const B64URL = /^[A-Za-z0-9_-]+={0,2}$/;
function validTimeZone(tz) {
if (typeof tz !== 'string' || tz.length === 0 || tz.length > 64) return false;
try {
new Intl.DateTimeFormat('en-US', { timeZone: tz });
return true;
} catch {
return false;
}
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const body = req.body || {};
const sub = body.subscription || {};
const keys = sub.keys || {};
const hour = Number(body.hour);
if (typeof sub.endpoint !== 'string' || sub.endpoint.length > 1000) {
return res.status(400).json({ error: 'Invalid subscription' });
}
let url;
try {
url = new URL(sub.endpoint);
} catch {
return res.status(400).json({ error: 'Invalid subscription' });
}
if (url.protocol !== 'https:') {
return res.status(400).json({ error: 'Invalid subscription' });
}
if (typeof keys.p256dh !== 'string' || keys.p256dh.length > 200 || !B64URL.test(keys.p256dh)) {
return res.status(400).json({ error: 'Invalid subscription keys' });
}
if (typeof keys.auth !== 'string' || keys.auth.length > 100 || !B64URL.test(keys.auth)) {
return res.status(400).json({ error: 'Invalid subscription keys' });
}
if (!Number.isInteger(hour) || hour < 0 || hour > 23) {
return res.status(400).json({ error: 'Hour must be 0 to 23' });
}
if (!validTimeZone(body.tz)) {
return res.status(400).json({ error: 'Invalid time zone' });
}
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
});
const { error } = await supabase.from('push_subs').upsert(
{
endpoint: sub.endpoint,
p256dh: keys.p256dh,
auth: keys.auth,
remind_hour: hour,
tz: body.tz
},
{ onConflict: 'endpoint' }
);
if (error) {
return res.status(500).json({ error: 'Could not save reminder' });
}
return res.status(200).json({ ok: true });
}api/unsubscribe.js · Deletes one phone's reminder when the buyer turns reminders off.
import { createClient } from '@supabase/supabase-js';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const endpoint = req.body && req.body.endpoint;
if (typeof endpoint !== 'string' || endpoint.length > 1000) {
return res.status(400).json({ error: 'Invalid endpoint' });
}
try {
if (new URL(endpoint).protocol !== 'https:') throw new Error('bad');
} catch {
return res.status(400).json({ error: 'Invalid endpoint' });
}
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
});
const { error } = await supabase.from('push_subs').delete().eq('endpoint', endpoint);
if (error) {
return res.status(500).json({ error: 'Could not remove reminder' });
}
return res.status(200).json({ ok: true });
}api/send-reminders.js · cron-job.org calls this every hour with the x-cron-secret header. It sends one reminder per phone per local day, at the hour the buyer chose. Edit the title and body text to your own words.
import { createClient } from '@supabase/supabase-js';
import webpush from 'web-push';
import { timingSafeEqual } from 'node:crypto';
const PAYLOAD = JSON.stringify({
title: 'Your 90 days',
body: 'Drink or no drink today? Tap to mark it.',
url: '/?mark=today'
});
function authorized(req) {
const expected = Buffer.from(process.env.CRON_SECRET || '');
const given = Buffer.from(String(req.headers['x-cron-secret'] || ''));
if (expected.length < 16 || given.length !== expected.length) return false;
return timingSafeEqual(given, expected);
}
function localParts(date, tz) {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
hourCycle: 'h23'
}).formatToParts(date);
const get = (type) => parts.find((p) => p.type === type).value;
return { day: `${get('year')}-${get('month')}-${get('day')}`, hour: Number(get('hour')) };
}
async function loadAll(supabase) {
const rows = [];
const size = 1000;
for (let from = 0; ; from += size) {
const { data, error } = await supabase
.from('push_subs')
.select('endpoint, p256dh, auth, remind_hour, tz, last_sent')
.order('endpoint')
.range(from, from + size - 1);
if (error) throw error;
rows.push(...data);
if (data.length < size) return rows;
}
}
export default async function handler(req, res) {
if (req.method !== 'GET' && req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
if (!authorized(req)) {
return res.status(401).json({ error: 'Unauthorized' });
}
webpush.setVapidDetails(
process.env.VAPID_SUBJECT,
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
});
let rows;
try {
rows = await loadAll(supabase);
} catch {
return res.status(500).json({ error: 'Could not read subscriptions' });
}
const now = new Date();
const due = [];
for (const row of rows) {
let local;
try {
local = localParts(now, row.tz);
} catch {
continue;
}
if (local.hour === row.remind_hour && row.last_sent !== local.day) {
due.push({ row, day: local.day });
}
}
let sent = 0;
let removed = 0;
let failed = 0;
for (let i = 0; i < due.length; i += 50) {
const batch = due.slice(i, i + 50);
await Promise.all(
batch.map(async ({ row, day }) => {
const sub = { endpoint: row.endpoint, keys: { p256dh: row.p256dh, auth: row.auth } };
try {
await webpush.sendNotification(sub, PAYLOAD, { TTL: 3600 });
await supabase.from('push_subs').update({ last_sent: day }).eq('endpoint', row.endpoint);
sent += 1;
} catch (err) {
if (err && (err.statusCode === 404 || err.statusCode === 410)) {
await supabase.from('push_subs').delete().eq('endpoint', row.endpoint);
removed += 1;
} else {
failed += 1;
}
}
})
);
}
return res.status(200).json({ checked: rows.length, sent, removed, failed });
}sw.js · Service worker: offline app shell, push notifications and notification taps. Change CACHE to ninety-v2, v3 and so on each time you publish changes.
const CACHE = 'ninety-v1';
const SHELL = [
'/',
'/index.html',
'/styles.css',
'/app.js',
'/manifest.json',
'/content/questions.json',
'/content/weeks.json',
'/content/tips.json',
'/vendor/jspdf.umd.min.js',
'/icons/icon-192.png',
'/icons/icon-512.png',
'/icons/apple-touch-icon.png'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (event) => {
const req = event.request;
const url = new URL(req.url);
if (req.method !== 'GET' || url.origin !== self.location.origin || url.pathname.startsWith('/api/')) {
return;
}
if (req.mode === 'navigate') {
event.respondWith(fetch(req).catch(() => caches.match('/index.html')));
return;
}
event.respondWith(
caches.match(req).then((hit) => {
const fresh = fetch(req)
.then((resp) => {
if (resp.ok) {
const copy = resp.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
}
return resp;
})
.catch(() => hit);
return hit || fresh;
})
);
});
self.addEventListener('push', (event) => {
let data = {};
try {
data = event.data ? event.data.json() : {};
} catch {
data = {};
}
event.waitUntil(
self.registration.showNotification(data.title || 'Your 90 days', {
body: data.body || 'Drink or no drink today? Tap to mark it.',
icon: '/icons/icon-192.png',
data: { url: data.url || '/?mark=today' }
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const path = (event.notification.data && event.notification.data.url) || '/?mark=today';
const target = new URL(path, self.location.origin).href;
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
for (const client of list) {
if ('focus' in client) {
client.postMessage({ type: 'mark-today' });
return client.focus();
}
}
return self.clients.openWindow(target);
})
);
});manifest.json · Makes the app installable. Change name and short_name when you pick the final name.
{
"name": "The 90 Day Alcohol-Free Guide",
"short_name": "90 Days",
"description": "Your why, your game plan and a daily drink or no drink tracker, by the creator.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#FFFFFF",
"theme_color": "#E0338A",
"icons": [
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
]
}package.json · Two libraries for the server functions. The app itself uses no npm packages.
{
"name": "ninety-days",
"private": true,
"type": "module",
"engines": { "node": ">=18" },
"dependencies": {
"@supabase/supabase-js": "^2.45.0",
"web-push": "^3.6.7"
}
}.env.example · Names only. Put the real values in Vercel, under Project Settings, Environment Variables. Never commit real values.
# Supabase: Project Settings, API
SUPABASE_URL=
SUPABASE_SERVICE_ROLE_KEY=
# From: npx web-push generate-vapid-keys
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
# Your contact, for example mailto:you@yourdomain.com
VAPID_SUBJECT=
# Random string, 32 characters, also set as the x-cron-secret header in cron-job.org
CRON_SECRET=
# One or more access codes separated by commas
ACCESS_CODES=
content/questions.json · Your 10 questions with the suggested edits to questions 1, 2, 3 and 7. Change the wording if you prefer.
{
"sections": [
{
"id": "why",
"title": "Before you start: your why",
"questions": [
{ "id": "q1", "text": "Why am I doing 90 days alcohol-free?" },
{ "id": "q2", "text": "What's one thing I want to prove to myself in these 90 days?" },
{ "id": "q3", "text": "How am I going to feel once I've completed 90 days?" },
{ "id": "q4", "text": "Am I going to tell people I'm doing this? Who?" },
{ "id": "q5", "text": "Who can I text if this gets difficult?" }
]
},
{
"id": "plan",
"title": "Your game plan",
"questions": [
{ "id": "q6", "text": "What social events have I got coming up where I'd normally drink?" },
{ "id": "q7", "text": "When I'm out, what non-alcoholic drink will I order instead?" },
{ "id": "q8", "text": "What will I say if someone asks why I'm not drinking?" },
{ "id": "q9", "text": "If I want to leave early, what's my exit plan?" },
{ "id": "q10", "text": "What will I do instead on the nights I'd normally drink?" }
]
}
]
}content/weeks.json · Weeks 1 to 4 come from your guide. Weeks 5 to 13 are placeholders: replace every WRITE line with your own words before launch.
[
{ "week": 1, "name": "The Adjustment", "noticed": ["Sleep gets better fast.", "Hangovers disappear.", "Mood can dip before it lifts."], "focus": "Rest.", "question": "What surprised me most this week?" },
{ "week": 2, "name": "The Dip", "noticed": ["Skin starts to clear.", "Energy is patchy.", "The feelings show up."], "focus": "Lean on people, don't isolate.", "question": "What am I most looking forward to?" },
{ "week": 3, "name": "The Shift", "noticed": ["Mood becomes steady.", "You notice what you actually enjoy.", "Social stuff gets easier."], "focus": "Find a replacement ritual. For me, it was movement.", "question": "What does a good Saturday morning look like without a hangover?" },
{ "week": 4, "name": "The Glow Up", "noticed": ["You feel like yourself again.", "Confidence feels real.", "You see who's really in your corner."], "focus": "Flick back to your why.", "question": "What do I want to keep doing after day 31?" },
{ "week": 5, "name": "WRITE: week 5 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 6, "name": "WRITE: week 6 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 7, "name": "WRITE: week 7 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 8, "name": "WRITE: week 8 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 9, "name": "WRITE: week 9 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 10, "name": "WRITE: week 10 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 11, "name": "WRITE: week 11 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 12, "name": "WRITE: week 12 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" },
{ "week": 13, "name": "WRITE: week 13 name", "noticed": ["WRITE", "WRITE", "WRITE"], "focus": "WRITE", "question": "WRITE" }
]content/tips.json · Your disclaimer, hard-day ideas, bar lines and check-in questions as written. Lines marked WRITE are for you to write.
{
"disclaimer": "This guide is based on my personal experience. It is not medical advice. If you're physically dependent on alcohol, stopping suddenly can present complications, so seek professional help.",
"welcome": "WRITE: your welcome for the 90-day version. Your original starts: I'm the creator. I've been alcohol-free for over two and a half years.",
"hardTips": [
{ "title": "Discomfort doesn't mean it's wrong.", "text": "WRITE: one sentence explaining this." },
{ "title": "Most of the fear isn't your own.", "text": "WRITE: one sentence explaining this." },
{ "title": "Confidence comes after, not before.", "text": "WRITE: one sentence explaining this." }
],
"hardClose": "When it gets really hard, text the person you named:",
"barLines": [
"I'm not drinking tonight.",
"Can I get a soda, lime and loads of ice? In a short glass.",
"I feel so much better without it."
],
"trackerTagline": "What gets measured gets managed.",
"checkin": [
"What did I overcome this week and what got me through it?",
"Did anything catch me off guard and what will I do differently?",
"What's coming up next week that I need a plan for?"
],
"drinkDay": "WRITE: a short, kind line for drink days.",
"day31": "Well done. Made it to 31. WRITE: one line about the next 59 days.",
"day90": "WRITE: your day 90 message.",
"signoff": "Come find me @yourhandle"
}