Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

add subscription page UI

daniel31x139159c496df18
diff --git a/apps/mobile/app/(tabs)/_layout.tsx b/apps/mobile/app/(tabs)/_layout.tsx
index 7233ad3b..e8e4ee72 100644
--- a/apps/mobile/app/(tabs)/_layout.tsx
+++ b/apps/mobile/app/(tabs)/_layout.tsx
@@ -1,13 +1,40 @@
-import { Tabs } from "expo-router";
-import React from "react";
-import { Platform } from "react-native";
+import { Tabs, useRouter } from "expo-router";
+import React, { useEffect } from "react";
+import { ActivityIndicator, Platform, View } from "react-native";
import TabBarBackground from "@/components/ui/TabBarBackground";
import { useColorScheme } from "nativewind";
import { rawTheme, ThemeName } from "@/lib/colors";
import { Folder, Hash, House, Link, Settings } from "lucide-react-native";
+import useAuthStore from "@/store/auth";
+import { useUser } from "@linkwarden/router/user";
+import { useConfig } from "@linkwarden/router/config";
+import { shouldRouteToSubscribe } from "@/lib/subscription";
export default function TabLayout() {
const { colorScheme } = useColorScheme();
+ const router = useRouter();
+ const { auth } = useAuthStore();
+ const { data: user, isLoading: isUserLoading } = useUser(auth);
+ const config = useConfig(auth);
+ const routeToSubscribe = shouldRouteToSubscribe(user, config.data);
+
+ useEffect(() => {
+ if (routeToSubscribe) router.replace("/subscribe");
+ }, [routeToSubscribe, router]);
+
+ if (
+ auth.status === "authenticated" &&
+ (isUserLoading || config.isLoading || routeToSubscribe)
+ ) {
+ return (
+ <View className="flex-1 items-center justify-center bg-base-100">
+ <ActivityIndicator
+ size="large"
+ color={rawTheme[colorScheme as ThemeName]["base-content"]}
+ />
+ </View>
+ );
+ }
return (
<Tabs
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 611d800e..005361ea 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -146,6 +146,7 @@ const RootComponent = ({ isLoading }: { isLoading: boolean }) => {
/>
<Stack.Screen name="login" />
<Stack.Screen name="register" />
+ <Stack.Screen name="subscribe" />
<Stack.Screen name="index" />
<Stack.Screen name="incoming" />
<Stack.Screen name="+not-found" />
diff --git a/apps/mobile/app/login.tsx b/apps/mobile/app/login.tsx
index 5e08a4c9..fca9ce04 100644
--- a/apps/mobile/app/login.tsx
+++ b/apps/mobile/app/login.tsx
@@ -8,7 +8,7 @@ import {
} from "@linkwarden/router/config";
import * as AppleAuthentication from "expo-apple-authentication";
import { GoogleSigninButton } from "@react-native-google-signin/google-signin";
-import { Redirect, router } from "expo-router";
+import { router } from "expo-router";
import { useColorScheme } from "nativewind";
import { useEffect, useState } from "react";
import {
@@ -126,9 +126,7 @@ export default function HomeScreen() {
};
}, [instance]);
- if (auth.status === "authenticated") {
- return <Redirect href="/dashboard" />;
- }
+ if (auth.status === "authenticated") return null;
return (
<>
diff --git a/apps/mobile/app/register.tsx b/apps/mobile/app/register.tsx
index db6c804e..4b74e4bc 100644
--- a/apps/mobile/app/register.tsx
+++ b/apps/mobile/app/register.tsx
@@ -8,7 +8,7 @@ import {
} from "@linkwarden/router/config";
import * as AppleAuthentication from "expo-apple-authentication";
import { GoogleSigninButton } from "@react-native-google-signin/google-signin";
-import { Redirect, router } from "expo-router";
+import { router } from "expo-router";
import { useColorScheme } from "nativewind";
import { useEffect, useState } from "react";
import {
@@ -39,6 +39,9 @@ const cloudConfig: Config = {
USER_CONTENT_DOMAIN: null,
AI_ENABLED: null,
INSTANCE_VERSION: null,
+ STRIPE_ENABLED: null,
+ TRIAL_PERIOD_DAYS: null,
+ REQUIRE_CC: null,
};
const cleanInstance = (instance: string) => instance.trim().replace(/\/+$/, "");
@@ -199,7 +202,8 @@ export default function RegisterScreen() {
if (!active || !configRes.ok || !loginsRes.ok) return;
- const config = ((await configRes.json())?.response ?? null) as Config | null;
+ const config = ((await configRes.json())?.response ??
+ null) as Config | null;
const logins = await loginsRes.json().catch(() => null);
const versionOk = isAtLeastInstanceVersion(
config?.INSTANCE_VERSION,
@@ -230,9 +234,7 @@ export default function RegisterScreen() {
};
}, [instance]);
- if (auth.status === "authenticated") {
- return <Redirect href="/dashboard" />;
- }
+ if (auth.status === "authenticated") return null;
const register = async () => {
const email = form.email.toLowerCase().trim();
diff --git a/apps/mobile/app/subscribe.tsx b/apps/mobile/app/subscribe.tsx
new file mode 100644
index 00000000..2c1e7acf
--- /dev/null
+++ b/apps/mobile/app/subscribe.tsx
@@ -0,0 +1,243 @@
+import { Button } from "@/components/ui/Button";
+import { rawTheme, ThemeName } from "@/lib/colors";
+import {
+ getSubscriptionDaysLeft,
+ getTrialPeriodDays,
+ hasInactiveSubscription,
+ shouldRouteToSubscribe,
+} from "@/lib/subscription";
+import useAuthStore from "@/store/auth";
+import { useConfig } from "@linkwarden/router/config";
+import { useUser } from "@linkwarden/router/user";
+import { Plan } from "@linkwarden/types/global";
+import { router } from "expo-router";
+import { useColorScheme } from "nativewind";
+import FontAwesome5 from "@expo/vector-icons/FontAwesome5";
+import { useEffect, useMemo, useState } from "react";
+import {
+ ActivityIndicator,
+ Dimensions,
+ Image,
+ Platform,
+ ScrollView,
+ Text,
+ TouchableOpacity,
+ View,
+} from "react-native";
+import { SafeAreaView } from "react-native-safe-area-context";
+import Svg, { Path } from "react-native-svg";
+
+const screenWidth = Dimensions.get("screen").width;
+
+const paymentButton = Platform.select({
+ ios: {
+ accessibilityLabel: "Subscribe with Apple Pay",
+ icon: "apple-pay",
+ iconSize: 50,
+ },
+ android: {
+ accessibilityLabel: "Subscribe with Google Pay",
+ icon: "google-pay",
+ iconSize: 50,
+ },
+ default: {
+ accessibilityLabel: "Complete Subscription",
+ iconSize: 0,
+ label: "Complete Subscription",
+ },
+});
+
+export default function SubscribeScreen() {
+ const { auth, signOut } = useAuthStore();
+ const { colorScheme } = useColorScheme();
+ const [plan, setPlan] = useState<Plan>(Plan.yearly);
+ const { data: user, isLoading: isUserLoading } = useUser(auth);
+ const config = useConfig(auth);
+
+ const trialPeriodDays = getTrialPeriodDays(config.data);
+ const daysLeft = getSubscriptionDaysLeft(user?.createdAt, trialPeriodDays);
+ const isForcedSubscribe = shouldRouteToSubscribe(user, config.data);
+ const showSubscribe = hasInactiveSubscription(user, config.data);
+ const isChecking =
+ auth.status === "loading" ||
+ (auth.status === "authenticated" && (isUserLoading || config.isLoading));
+
+ useEffect(() => {
+ if (auth.status === "unauthenticated") router.replace("/");
+ if (auth.status === "authenticated" && !isChecking && !showSubscribe)
+ router.replace("/(tabs)/dashboard");
+ }, [auth.status, isChecking, showSubscribe]);
+
+ const selectedPlan = useMemo(() => {
+ const isMonthly = plan === Plan.monthly;
+ const deferredDays = config.data?.REQUIRE_CC ? trialPeriodDays : daysLeft;
+
+ return {
+ price: isMonthly ? "4" : "3",
+ billed: isMonthly ? "Billed monthly" : "Billed yearly",
+ total:
+ deferredDays > 0
+ ? `After ${deferredDays} ${deferredDays === 1 ? "day" : "days"}: ${
+ isMonthly ? "$4 per month" : "$36 per year"
+ }, plus tax.`
+ : `${isMonthly ? "$4 per month" : "$36 per year"}, plus tax.`,
+ };
+ }, [config.data?.REQUIRE_CC, daysLeft, plan, trialPeriodDays]);
+
+ if (isChecking || auth.status !== "authenticated" || !showSubscribe) {
+ return (
+ <View className="flex-1 items-center justify-center bg-base-100">
+ <ActivityIndicator
+ size="large"
+ color={rawTheme[colorScheme as ThemeName]["base-content"]}
+ />
+ </View>
+ );
+ }
+
+ const trialText = config.data?.REQUIRE_CC
+ ? `Start with a ${trialPeriodDays}-day free trial, cancel anytime.`
+ : daysLeft <= 0
+ ? "Your free trial has ended. Subscribe to continue."
+ : `You have ${daysLeft} ${
+ daysLeft === 1 ? "day" : "days"
+ } left in your free trial.`;
+
+ return (
+ <ScrollView
+ className="bg-primary"
+ contentContainerStyle={{ flexGrow: 1 }}
+ bounces={false}
+ >
+ <View className="flex-1 justify-end bg-primary">
+ <SafeAreaView edges={["top"]} className="flex-1 justify-center px-8">
+ <Image
+ source={require("@/assets/images/linkwarden.png")}
+ className="w-[104px] h-[104px]"
+ />
+ <Text className="text-base-100 text-5xl font-bold mt-8">
+ Subscribe
+ </Text>
+ <Text className="text-base-100 text-2xl mt-3">{trialText}</Text>
+ </SafeAreaView>
+
+ <Svg
+ viewBox="0 0 1440 320"
+ width={screenWidth}
+ height={screenWidth * (320 / 1440) + 2}
+ >
+ <Path
+ fill={rawTheme[colorScheme as ThemeName]["base-100"]}
+ fillOpacity="1"
+ d="M0,256L48,234.7C96,213,192,171,288,176C384,181,480,235,576,266.7C672,299,768,309,864,277.3C960,245,1056,171,1152,122.7C1248,75,1344,53,1392,42.7L1440,32L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"
+ />
+ </Svg>
+
+ <SafeAreaView
+ edges={["bottom"]}
+ className="bg-base-100 -mt-2 px-4 pt-8 pb-8 gap-5"
+ >
+ <Text className="text-base-content text-base">
+ Subscribe to start using Linkwarden. If you think this is a mistake,
+ </Text>
+
+ <View className="bg-base-200 border border-neutral-content rounded-lg p-1 flex-row relative">
+ <TouchableOpacity
+ activeOpacity={0.85}
+ onPress={() => setPlan(Plan.monthly)}
+ className={`flex-1 items-center rounded-md py-2 ${
+ plan === Plan.monthly ? "bg-primary" : ""
+ }`}
+ >
+ <Text
+ className={`text-base font-semibold ${
+ plan === Plan.monthly ? "text-base-100" : "text-base-content"
+ }`}
+ >
+ Monthly
+ </Text>
+ </TouchableOpacity>
+
+ <TouchableOpacity
+ activeOpacity={0.85}
+ onPress={() => setPlan(Plan.yearly)}
+ className={`flex-1 items-center rounded-md py-2 ${
+ plan === Plan.yearly ? "bg-primary" : ""
+ }`}
+ >
+ <Text
+ className={`text-base font-semibold ${
+ plan === Plan.yearly ? "text-base-100" : "text-base-content"
+ }`}
+ >
+ Yearly
+ </Text>
+ </TouchableOpacity>
+
+ <View
+ className="absolute -top-3 right-1 bg-red-600 px-2 py-0.5 rounded-md"
+ style={{ transform: [{ rotate: "12deg" }] }}
+ >
+ <Text className="text-white text-xs font-semibold">25% off</Text>
+ </View>
+ </View>
+
+ <View className="items-center gap-1">
+ <Text className="text-base-content text-4xl font-semibold">
+ ${selectedPlan.price}
+ <Text className="text-neutral text-base font-normal">/mo</Text>
+ </Text>
+ <Text className="text-base-content text-base font-semibold">
+ {selectedPlan.billed}
+ </Text>
+ </View>
+
+ <View className="border border-neutral-content rounded-lg p-3">
+ <Text className="text-base-content text-sm font-semibold mb-1">
+ Total
+ </Text>
+ <Text className="text-neutral text-sm">{selectedPlan.total}</Text>
+ </View>
+
+ <TouchableOpacity
+ activeOpacity={0.85}
+ accessibilityRole="button"
+ accessibilityLabel={paymentButton.accessibilityLabel}
+ className="w-full flex-row items-center justify-center rounded-lg bg-black px-4"
+ onPress={() => undefined}
+ >
+ {paymentButton.icon ? (
+ <FontAwesome5
+ brand
+ name={paymentButton.icon}
+ size={paymentButton.iconSize}
+ color="white"
+ />
+ ) : (
+ <Text className="text-xl font-semibold text-white">
+ {paymentButton.label}
+ </Text>
+ )}
+ </TouchableOpacity>
+
+ {isForcedSubscribe ? (
+ <TouchableOpacity className="w-fit mx-auto" onPress={signOut}>
+ <Text className="text-neutral text-center w-fit font-semibold">
+ Sign out
+ </Text>
+ </TouchableOpacity>
+ ) : (
+ <Button
+ variant="metal"
+ size="lg"
+ onPress={() => router.replace("/(tabs)/dashboard")}
+ >
+ <Text className="text-base-content text-xl">Subscribe Later</Text>
+ </Button>
+ )}
+ </SafeAreaView>
+ </View>
+ </ScrollView>
+ );
+}
diff --git a/apps/mobile/lib/subscription.ts b/apps/mobile/lib/subscription.ts
new file mode 100644
index 00000000..61e9f483
--- /dev/null
+++ b/apps/mobile/lib/subscription.ts
@@ -0,0 +1,55 @@
+import type { Config } from "@linkwarden/router/config";
+import type { GetUserByIdResponse } from "@linkwarden/types/global";
+
+const DEFAULT_TRIAL_PERIOD_DAYS = 14;
+
+const getTrialPeriodDays = (
+ config?: Pick<Config, "TRIAL_PERIOD_DAYS"> | null
+) => Number(config?.TRIAL_PERIOD_DAYS) || DEFAULT_TRIAL_PERIOD_DAYS;
+
+const getSubscriptionDaysLeft = (
+ createdAt?: string | Date | null,
+ trialPeriodDays = DEFAULT_TRIAL_PERIOD_DAYS
+) => {
+ if (!createdAt) return 0;
+
+ const createdAtTime = new Date(createdAt).getTime();
+ if (Number.isNaN(createdAtTime)) return 0;
+
+ const trialEndTime = createdAtTime + (1 + Number(trialPeriodDays)) * 86400000;
+
+ return Math.floor((trialEndTime - Date.now()) / 86400000);
+};
+
+const hasInactiveSubscription = (
+ user?: Partial<GetUserByIdResponse> | null,
+ config?: Config | null
+) => {
+ return Boolean(
+ user?.id &&
+ config?.STRIPE_ENABLED &&
+ !user?.subscription?.active &&
+ !user?.parentSubscription?.active
+ );
+};
+
+const shouldRouteToSubscribe = (
+ user?: Partial<GetUserByIdResponse> | null,
+ config?: Config | null
+) => {
+ const trialPeriodDays = getTrialPeriodDays(config);
+ const daysLeft = getSubscriptionDaysLeft(user?.createdAt, trialPeriodDays);
+
+ return Boolean(
+ hasInactiveSubscription(user, config) &&
+ (config?.REQUIRE_CC || daysLeft <= 0)
+ );
+};
+
+export {
+ DEFAULT_TRIAL_PERIOD_DAYS,
+ getTrialPeriodDays,
+ getSubscriptionDaysLeft,
+ hasInactiveSubscription,
+ shouldRouteToSubscribe,
+};
diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.ts
index 4ecc99fa..76feb63a 100644
--- a/apps/mobile/store/auth.ts
+++ b/apps/mobile/store/auth.ts
@@ -6,13 +6,15 @@ import {
statusCodes,
} from "@react-native-google-signin/google-signin";
import { router } from "expo-router";
-import { MobileAuth } from "@linkwarden/types/global";
+import type { GetUserByIdResponse, MobileAuth } from "@linkwarden/types/global";
+import type { Config } from "@linkwarden/router/config";
import { Alert } from "react-native";
import { queryClient } from "@/lib/queryClient";
import { mmkvPersister } from "@/lib/queryPersister";
import { clearCache } from "@/lib/cache";
import useDataStore from "@/store/data";
import { useOfflineSyncStore } from "@/lib/offlineSync";
+import { hasInactiveSubscription } from "@/lib/subscription";
const cloudInstance = "https://cloud.linkwarden.app";
const googleWebClientId =
@@ -59,6 +61,35 @@ const timeout = () =>
setTimeout(() => reject(new Error("TIMEOUT")), 30000)
);
+const getPostAuthRoute = async (instance: string, session: string) => {
+ try {
+ const headers = { Authorization: `Bearer ${session}` };
+ const [configRes, userRes] = await Promise.all([
+ Promise.race([
+ fetch(`${instance}/api/v1/config`, { headers }),
+ timeout(),
+ ]),
+ Promise.race([
+ fetch(`${instance}/api/v1/users/me`, { headers }),
+ timeout(),
+ ]),
+ ]);
+
+ if (!configRes.ok || !userRes.ok) return "/(tabs)/dashboard";
+
+ const config = ((await configRes.json())?.response ??
+ null) as Config | null;
+ const user = ((await userRes.json())?.response ??
+ null) as GetUserByIdResponse | null;
+
+ return hasInactiveSubscription(user, config)
+ ? "/subscribe"
+ : "/(tabs)/dashboard";
+ } catch {
+ return "/(tabs)/dashboard";
+ }
+};
+
const requestVerificationEmail = async (email: string, instance: string) => {
try {
const res = await Promise.race([
@@ -169,6 +200,8 @@ const useAuthStore = create<AuthStore>((set) => ({
]);
if (res.ok) {
+ const route = await getPostAuthRoute(instance, token);
+
await SecureStore.setItemAsync("INSTANCE", instance);
await SecureStore.setItemAsync("TOKEN", token);
set({
@@ -178,7 +211,7 @@ const useAuthStore = create<AuthStore>((set) => ({
status: "authenticated",
},
});
- router.replace("/(tabs)/dashboard");
+ router.replace(route);
} else {
Alert.alert("Error", "Invalid token");
}
@@ -211,11 +244,12 @@ const useAuthStore = create<AuthStore>((set) => ({
if (res.ok) {
const data = await res.json();
const session = (data as any).response.token;
+ const route = await getPostAuthRoute(instance, session);
await SecureStore.setItemAsync("TOKEN", session);
await SecureStore.setItemAsync("INSTANCE", instance);
set({ auth: { session, instance, status: "authenticated" } });
- router.replace("/(tabs)/dashboard");
+ router.replace(route);
} else {
Alert.alert("Error", "Invalid credentials");
}
@@ -278,10 +312,12 @@ const useAuthStore = create<AuthStore>((set) => ({
if (res.ok) {
const session = data.response.token;
+ const route = await getPostAuthRoute(instance, session);
+
await SecureStore.setItemAsync("TOKEN", session);
await SecureStore.setItemAsync("INSTANCE", instance);
set({ auth: { session, instance, status: "authenticated" } });
- router.replace("/(tabs)/dashboard");
+ router.replace(route);
} else {
Alert.alert("Error", data?.response || "Could not sign in with Apple.");
}
@@ -343,10 +379,12 @@ const useAuthStore = create<AuthStore>((set) => ({
if (res.ok) {
const session = data.response.token;
+ const route = await getPostAuthRoute(instance, session);
+
await SecureStore.setItemAsync("TOKEN", session);
await SecureStore.setItemAsync("INSTANCE", instance);
set({ auth: { session, instance, status: "authenticated" } });
- router.replace("/(tabs)/dashboard");
+ router.replace(route);
} else {
Alert.alert(
"Error",
diff --git a/apps/web/lib/api/verifyByCredentials.ts b/apps/web/lib/api/verifyByCredentials.ts
index d73ddd58..a5058159 100644
--- a/apps/web/lib/api/verifyByCredentials.ts
+++ b/apps/web/lib/api/verifyByCredentials.ts
@@ -1,6 +1,5 @@
import { prisma } from "@linkwarden/prisma";
import { User } from "@linkwarden/prisma/client";
-import verifySubscription from "./stripe/verifySubscription";
import bcrypt from "bcrypt";
type Props = {
@@ -53,13 +52,6 @@ export default async function verifyByCredentials({
if (!passwordMatches) {
return null;
} else {
- if (STRIPE_SECRET_KEY) {
- const subscribedUser = await verifySubscription(user);
-
- if (!subscribedUser) {
- return null;
- }
- }
return user;
}
} else {
diff --git a/apps/web/pages/api/v1/config/index.test.ts b/apps/web/pages/api/v1/config/index.test.ts
index a4f2b6cb..9326a0ed 100644
--- a/apps/web/pages/api/v1/config/index.test.ts
+++ b/apps/web/pages/api/v1/config/index.test.ts
@@ -22,4 +22,16 @@ describe("getEnvData", () => {
expect(getEnvData().USER_CONTENT_DOMAIN).toBeNull();
});
+
+ it("returns subscription config from the environment", () => {
+ vi.stubEnv("STRIPE_SECRET_KEY", "sk_test_123");
+ vi.stubEnv("NEXT_PUBLIC_TRIAL_PERIOD_DAYS", "30");
+ vi.stubEnv("NEXT_PUBLIC_REQUIRE_CC", "true");
+
+ expect(getEnvData()).toMatchObject({
+ STRIPE_ENABLED: true,
+ TRIAL_PERIOD_DAYS: 30,
+ REQUIRE_CC: true,
+ });
+ });
});
diff --git a/apps/web/pages/api/v1/config/index.ts b/apps/web/pages/api/v1/config/index.ts
index b664c47f..e854c56c 100644
--- a/apps/web/pages/api/v1/config/index.ts
+++ b/apps/web/pages/api/v1/config/index.ts
@@ -26,5 +26,12 @@ export const getEnvData = () => {
USER_CONTENT_DOMAIN: process.env.NEXT_PUBLIC_USER_CONTENT_DOMAIN || null,
AI_ENABLED: hasAiProvider || null,
INSTANCE_VERSION: process.env.version,
+ STRIPE_ENABLED:
+ process.env.NEXT_PUBLIC_STRIPE === "true" ||
+ Boolean(process.env.STRIPE_SECRET_KEY) ||
+ null,
+ TRIAL_PERIOD_DAYS:
+ Number(process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS) || null,
+ REQUIRE_CC: process.env.NEXT_PUBLIC_REQUIRE_CC === "true" || null,
};
};
diff --git a/packages/router/config.tsx b/packages/router/config.tsx
index 334c80d2..596e9869 100644
--- a/packages/router/config.tsx
+++ b/packages/router/config.tsx
@@ -10,6 +10,9 @@ export type Config = {
USER_CONTENT_DOMAIN: string | null;
AI_ENABLED: boolean | null;
INSTANCE_VERSION: string | null;
+ STRIPE_ENABLED: boolean | null;
+ TRIAL_PERIOD_DAYS: number | null;
+ REQUIRE_CC: boolean | null;
};
const normalizeVersion = (version?: string | null) => {
diff --git a/packages/router/dashboardData.tsx b/packages/router/dashboardData.tsx
index db1bda8d..07b91a64 100644
--- a/packages/router/dashboardData.tsx
+++ b/packages/router/dashboardData.tsx
@@ -28,6 +28,9 @@ const useDashboardData = (auth?: MobileAuth) => {
);
const data = await response.json();
+ if (!response.ok)
+ throw new Error(data?.response || "Failed to fetch dashboard data.");
+
return data.data;
},
enabled: status === "authenticated",