├── .env.local.example ├── .eslintrc.json ├── .gitignore ├── .nvmrc ├── LICENSE ├── README.md ├── atoms └── atoms.ts ├── components ├── AuthIsLoaded.tsx ├── Dropdown.tsx ├── FullScreenLoader.tsx ├── Hero.tsx ├── Modal.tsx ├── Packages.tsx ├── Spinner.tsx ├── UnauthorizedDomainError.tsx ├── Upload.tsx ├── UsageBar.tsx └── layout │ ├── Container.tsx │ ├── Footer.tsx │ ├── Header.tsx │ └── Layout.tsx ├── lib ├── auth.ts ├── const.ts ├── download.ts ├── firebase.ts ├── get-schema.ts ├── packages.ts ├── profiles.ts ├── storage.ts └── types.ts ├── next.config.js ├── package-lock.json ├── package.json ├── pages ├── _app.tsx ├── _document.tsx ├── dashboard.tsx ├── index.tsx ├── packages.tsx └── remove.tsx ├── postcss.config.js ├── public ├── avatar.png ├── favicon.ico ├── input.jpeg ├── next.svg ├── output.jpeg ├── photo.svg ├── rowy.png ├── screenshot.jpeg ├── thirteen.svg └── vercel.svg ├── styles ├── Satoshi-Black.ttf ├── Satoshi-Bold.ttf ├── Satoshi-Variable.woff2 └── globals.css ├── tailwind.config.js └── tsconfig.json /.env.local.example: -------------------------------------------------------------------------------- 1 | REPLICATE_API_TOKEN= 2 | STRIPE_SECRET_KEY= 3 | 4 | # Firebase specific envs 5 | NEXT_PUBLIC_FIREBASE_API_KEY= 6 | NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN= 7 | NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET= 8 | NEXT_PUBLIC_FIREBASE_SENDER_ID= 9 | NEXT_PUBLIC_FIREBASE_APP_ID= 10 | NEXT_PUBLIC_FIREBASE_PROJECT_ID= 11 | 12 | 13 | # Rowy specific envs 14 | NEXT_PUBLIC_PROFILES_TABLE_ID= 15 | 16 | NEXT_PUBLIC_START_PREDICTION_WEBHOOK= 17 | NEXT_PUBLIC_CREATE_STRIPE_CHECKOUT_WEBHOOK= 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals" 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | .pnpm-debug.log* 27 | 28 | # local env files 29 | .env*.local 30 | 31 | # vercel 32 | .vercel 33 | 34 | # typescript 35 | *.tsbuildinfo 36 | next-env.d.ts 37 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 18.14.0 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AI MicroSaaS Template 2 | ## Background Removal App 3 | 4 | This project allows users to remove the background from their photos using AI and comes integrated with Stripe payment. You can clone this project to create a AI MicroSaaS project and easily modify it for any usecase. 5 | 6 | [![Remove Background App](./public/screenshot.jpeg)](https://demo-microsaas.vercel.app/) 7 | 8 | ## Stack used 9 | 10 | **App Frontend**: Next.js 11 | **Database**: Firebase 12 | **CMS**: Rowy 13 | **Auth**: Firebase Auth 14 | **Payment**: Stripe 15 | **CSS**: Tailwind 16 | **Usecase**: Subscription, SaaS, AI, MicroSaaS 17 | 18 | ### Try it here: [Live Demo](https://demo-microsaas.vercel.app/) 19 | 20 | ## How it works 21 | 22 | This app uses the [modnet](https://github.com/pollinations/modnet) API via [Replicate](https://replicate.com/) to remove the background of images. Once users upload images, these images first gets stored to Firebase storage and then using low-code Cloud Functions built with [Rowy](https://www.rowy.io?ref=microsaas), the image's background is removed by making API call to Replicate which returns the photo with its background removed. 23 | 24 | User authentication is managed via Firebase Auth and managed easily on User management table of Rowy. All data such as user profile, generated images, and credit packges are stored in Firestore, while the associated stripe payment webhook and cloud functions are all managed in [Rowy](https://www.rowy.io?ref=microsaas). 25 | 26 | This app also has Stripe payment integrated with webhooks built in low-code using Rowy, with the following plan that can be easily customized. 27 | - Without account creation → 10 free credits 28 | - With logged in users → unlock 100 credits along with ability to track paid users 29 | 30 | ## Get started quickly using fullstack template 31 | 32 | ### Frontend Template 33 | 1. Clone and deploy the Next.js App using Vercel's one click deploy link below 34 | 2. Add the .env variables as shown in the .env.local.example file 35 | 36 | One-Click deploy using [Vercel](https://vercel.com): 37 | 38 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/rowyio/demo-microsaas&env=REPLICATE_API_TOKEN,STRIPE_SECRET_KEY,NEXT_PUBLIC_FIREBASE_API_KEY,NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,NEXT_PUBLIC_FIREBASE_SENDER_ID,NEXT_PUBLIC_FIREBASE_APP_ID,NEXT_PUBLIC_FIREBASE_PROJECT_ID,NEXT_PUBLIC_PROFILES_TABLE_ID,NEXT_PUBLIC_START_PREDICTION_WEBHOOK,NEXT_PUBLIC_CREATE_STRIPE_CHECKOUT_WEBHOOK&project-name=demo-microsaas&repo-name=demo-microsaas) 39 | 40 | ### Backend Template 41 | 1. Create an account on [Rowy](https://www.rowy.io?ref=microsaas) 42 | 2. On your workspace, create a Firebase project right from Rowy's guided UI. 43 | 3. Create a table from the `AI background remover` template - this will give you a guided setup experience to create database table for storing your app data including Firebase Auth authenticated users as well as steps to add [Replicate](https://replicate.com/) API key along with deploying pre-built backend Cloud Functions for Replicate and Stripe payments. 44 | -------------------------------------------------------------------------------- /atoms/atoms.ts: -------------------------------------------------------------------------------- 1 | import { atom } from "jotai"; 2 | import { Auth, Credits } from "../lib/types"; 3 | 4 | export const initialAuthState: Auth = { 5 | isAuthenticated: false, 6 | }; 7 | 8 | export const initialCreditsState: Credits = { 9 | used: 0, 10 | limit: 0, 11 | }; 12 | 13 | export const userAuthAtom = atom(initialAuthState); 14 | 15 | export const creditsAtom = atom(initialCreditsState); 16 | -------------------------------------------------------------------------------- /components/AuthIsLoaded.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | creditsAtom, 3 | initialAuthState, 4 | initialCreditsState, 5 | userAuthAtom, 6 | } from "@/atoms/atoms"; 7 | import { anonymouslySignIn, formatUser } from "@/lib/auth"; 8 | import { auth, db } from "@/lib/firebase"; 9 | import { getSchema } from "@/lib/get-schema"; 10 | import { getOrCreateProfile } from "@/lib/profiles"; 11 | import { Auth, ProfilePackage } from "@/lib/types"; 12 | import { onAuthStateChanged } from "firebase/auth"; 13 | import { doc, onSnapshot } from "firebase/firestore"; 14 | import { useAtom, useSetAtom } from "jotai"; 15 | import { ReactNode, useEffect, useState } from "react"; 16 | 17 | export default function AuthIsLoaded({ children }: { children: ReactNode }) { 18 | const [userAuth, setUserAuth] = useAtom(userAuthAtom); 19 | const setCredits = useSetAtom(creditsAtom); 20 | const [loading, setLoading] = useState(true); 21 | 22 | useEffect(() => { 23 | const unsubscribe = onAuthStateChanged(auth, async (user) => { 24 | if (user) { 25 | const formattedUser = await formatUser(user); 26 | const profile = await getOrCreateProfile( 27 | user.uid, 28 | formattedUser.isAnonymous 29 | ); 30 | 31 | if (profile) { 32 | const authState: Auth = { 33 | user: { 34 | id: profile.id, 35 | userId: formattedUser.uid, 36 | token: formattedUser.token, 37 | expirationTime: formattedUser.expirationTime, 38 | isAnonymous: formattedUser.isAnonymous, 39 | photoUrl: formattedUser.photoUrl, 40 | }, 41 | isAuthenticated: !user.isAnonymous, 42 | }; 43 | setUserAuth(authState); 44 | setCredits(profile.data().package); 45 | setLoading(false); 46 | } 47 | } else { 48 | anonymouslySignIn(); 49 | 50 | // User is signed out, sign in anonymous user 51 | setUserAuth(initialAuthState); 52 | setCredits(initialCreditsState); 53 | setLoading(false); 54 | } 55 | }); 56 | return () => { 57 | unsubscribe(); 58 | }; 59 | }, [setCredits, setUserAuth]); 60 | 61 | useEffect(() => { 62 | async function onProfileChange() { 63 | if (userAuth.user) { 64 | const { tableEnv } = await getSchema(); 65 | const unsub = onSnapshot( 66 | doc( 67 | db, 68 | tableEnv.collectionIds["microSaaSProfiles"], 69 | userAuth.user.id 70 | ), 71 | (doc) => { 72 | const profile = doc.data(); 73 | if (profile) { 74 | const { used, limit } = profile.package as ProfilePackage; 75 | setCredits({ used, limit }); 76 | } 77 | } 78 | ); 79 | 80 | return () => { 81 | unsub(); 82 | }; 83 | } 84 | } 85 | onProfileChange(); 86 | }, [userAuth.user, setCredits]); 87 | 88 | // useEffect(() => { 89 | // signOut(auth); 90 | // }, []); 91 | 92 | return <>{children}; 93 | } 94 | -------------------------------------------------------------------------------- /components/Dropdown.tsx: -------------------------------------------------------------------------------- 1 | import { userAuthAtom } from "@/atoms/atoms"; 2 | import { auth } from "@/lib/firebase"; 3 | import { signOut } from "firebase/auth"; 4 | import { useAtomValue } from "jotai"; 5 | import Image from "next/image"; 6 | import Link from "next/link"; 7 | import { useRouter } from "next/router"; 8 | import { useEffect, useRef, useState } from "react"; 9 | 10 | export default function Dropdown() { 11 | const [isOpen, setIsOpen] = useState(false); 12 | const { user, isAuthenticated } = useAtomValue(userAuthAtom); 13 | const router = useRouter(); 14 | const dropdownRef = useRef(null); 15 | 16 | const toggleDropdown = () => { 17 | setIsOpen(!isOpen); 18 | }; 19 | 20 | const handleClickOutside = (event: MouseEvent) => { 21 | event.target; 22 | if ( 23 | dropdownRef.current && 24 | event.target instanceof HTMLElement && 25 | !dropdownRef.current.contains(event.target) 26 | ) { 27 | setIsOpen(false); 28 | } 29 | }; 30 | 31 | const onLinkClick = () => { 32 | setIsOpen(false); 33 | toggleDropdown(); 34 | }; 35 | 36 | const logout = () => { 37 | signOut(auth) 38 | .then(() => { 39 | // Sign-out successful. 40 | console.log("Signed out successfully"); 41 | // location.replace("/"); 42 | router.push("/"); 43 | }) 44 | .catch((error) => { 45 | // An error happened. 46 | console.log("Signed out failed", error); 47 | }); 48 | }; 49 | 50 | useEffect(() => { 51 | document.addEventListener("click", handleClickOutside, true); 52 | return () => { 53 | document.removeEventListener("click", handleClickOutside, true); 54 | }; 55 | }, []); 56 | 57 | return ( 58 |
59 | 80 | {isOpen && ( 81 |
82 | 87 | Dashboard 88 | 89 | 94 | Packages 95 | 96 | { 100 | logout(); 101 | onLinkClick(); 102 | }} 103 | > 104 | Sign out 105 | 106 |
107 | )} 108 |
109 | ); 110 | } 111 | -------------------------------------------------------------------------------- /components/FullScreenLoader.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from "react"; 2 | import Spinner from "./Spinner"; 3 | 4 | export default function FullScreenLoader({ 5 | text, 6 | isOpen, 7 | }: { 8 | text: string; 9 | isOpen: boolean; 10 | }) { 11 | useEffect(() => { 12 | const body = document.querySelector("body"); 13 | 14 | if (isOpen) { 15 | body?.classList.add("fullscreen-active"); 16 | } else { 17 | body?.classList.remove("fullscreen-active"); 18 | } 19 | }, [isOpen]); 20 | 21 | if (!isOpen) return null; 22 | 23 | return ( 24 |
25 |
26 |

{text}

27 | 28 |
29 |
30 | ); 31 | } 32 | -------------------------------------------------------------------------------- /components/Hero.tsx: -------------------------------------------------------------------------------- 1 | import Link from "next/link"; 2 | import Container from "./layout/Container"; 3 | 4 | type Props = { 5 | heading: string; 6 | subHeading: string; 7 | link?: { title: string; to: string }; 8 | alignment?: "left" | "right" | "center"; 9 | showSeparator?: boolean; 10 | className?: string; 11 | }; 12 | 13 | export default function Hero({ 14 | className = "", 15 | heading, 16 | subHeading, 17 | link, 18 | alignment = "left", 19 | showSeparator = true, 20 | }: Props) { 21 | return ( 22 |
27 | 28 |

29 | 30 | {heading} 31 | 32 |

33 |

{subHeading}

34 | {link && ( 35 | 36 | 39 | 40 | )} 41 |
42 |
43 | ); 44 | } 45 | -------------------------------------------------------------------------------- /components/Modal.tsx: -------------------------------------------------------------------------------- 1 | import { ReactNode, useEffect } from "react"; 2 | import ReactModal from "react-modal"; 3 | 4 | const customStyles = { 5 | content: { 6 | top: "40%", 7 | left: "50%", 8 | right: "auto", 9 | bottom: "auto", 10 | marginRight: "-50%", 11 | transform: "translate(-50%, -50%)", 12 | }, 13 | }; 14 | 15 | ReactModal.setAppElement("#modal"); 16 | 17 | ReactModal.defaultStyles.content!.background = "none"; 18 | ReactModal.defaultStyles.content!.minWidth = "500px"; 19 | ReactModal.defaultStyles.content!.maxWidth = "600px"; 20 | ReactModal.defaultStyles.content!.border = "none"; 21 | ReactModal.defaultStyles.overlay!.background = "rgba(0, 0, 0, 0.3)"; 22 | 23 | type Props = { 24 | isOpen: boolean; 25 | title: string; 26 | onClose: () => void; 27 | children?: ReactNode; 28 | }; 29 | 30 | export default function Modal({ isOpen, title, children, onClose }: Props) { 31 | useEffect(() => { 32 | const body = document.querySelector("body"); 33 | if (body) body.style.overflow = isOpen ? "hidden" : "auto"; 34 | }, [isOpen]); 35 | return ( 36 |
37 | 43 |
44 |
45 |
46 |

{title}

47 | 67 |
68 |
{children}
69 |
70 |
71 |
72 |
73 | ); 74 | } 75 | -------------------------------------------------------------------------------- /components/Packages.tsx: -------------------------------------------------------------------------------- 1 | import { userAuthAtom } from "@/atoms/atoms"; 2 | import { db } from "@/lib/firebase"; 3 | import { getPackages } from "@/lib/packages"; 4 | import { Package } from "@/lib/types"; 5 | import { collection, orderBy, query } from "firebase/firestore"; 6 | import { useAtomValue } from "jotai"; 7 | import { useEffect, useState } from "react"; 8 | import { getSchema } from "@/lib/get-schema"; 9 | import { CREATE_STRIPE_CHECKOUT_ENDPOINT } from "@/lib/const"; 10 | import Spinner from "./Spinner"; 11 | 12 | export default function Packages() { 13 | const [loading, setLoading] = useState(false); 14 | const [loadingPackages, setLoadingPackages] = useState(false); 15 | const { user } = useAtomValue(userAuthAtom); 16 | const [packages, setPackages] = useState(); 17 | 18 | const purchase = async (creditPackage: Package) => { 19 | setLoading(true); 20 | try { 21 | const response = await fetch(CREATE_STRIPE_CHECKOUT_ENDPOINT, { 22 | method: "POST", 23 | headers: { 24 | "Content-Type": "application/json", 25 | token: `${user?.token}`, 26 | }, 27 | body: JSON.stringify({ creditPackage, profileId: user?.id }), 28 | }); 29 | 30 | if (response.ok) { 31 | const data = (await response.json()) as { url: string }; 32 | const win: Window = window; 33 | win.location = data.url; 34 | } 35 | } catch (error) { 36 | console.log("checkout error", error); 37 | } finally { 38 | setLoading(false); 39 | } 40 | }; 41 | 42 | useEffect(() => { 43 | const loadPackages = async () => { 44 | setLoadingPackages(true); 45 | const { tableEnv } = await getSchema(); 46 | 47 | const packagesQuery = query( 48 | collection(db, tableEnv.collectionIds["microSaaSPackages"]), 49 | orderBy("price", "asc") 50 | ); 51 | const packagesSnapshot = await getPackages(packagesQuery); 52 | const allPackages = packagesSnapshot.map((item) => ({ 53 | ...item.data(), 54 | id: item.id, 55 | })) as Package[]; 56 | // Filter out free package 57 | const filteredPackages = allPackages.filter((item) => item.price !== 0); 58 | setPackages(filteredPackages); 59 | setLoadingPackages(false); 60 | }; 61 | loadPackages(); 62 | }, []); 63 | 64 | if (loadingPackages) 65 | return ( 66 |
67 | 68 |
69 | ); 70 | 71 | return ( 72 |
73 | {packages && 74 | packages.map((pack) => ( 75 |
79 |
80 |
81 |

${pack.price}

82 | {pack.price === 0 && ( 83 |
84 | Free 85 |
86 | )} 87 |
88 |

{pack.limit} Credits

89 | 96 |
97 |
98 | ))} 99 |
100 | ); 101 | } 102 | -------------------------------------------------------------------------------- /components/Spinner.tsx: -------------------------------------------------------------------------------- 1 | export default function Spinner() { 2 | return ( 3 |
4 | 20 | Loading... 21 |
22 | ); 23 | } 24 | -------------------------------------------------------------------------------- /components/UnauthorizedDomainError.tsx: -------------------------------------------------------------------------------- 1 | import { AlertCircle } from "tabler-icons-react"; 2 | 3 | export default function UnauthorizedDomainError() { 4 | return ( 5 |
6 |
7 | 8 |

Firebase unauthorized domain

9 |
10 | 11 |
12 | If you are the app developer{" "} 13 | 18 | click here 19 | {" "} 20 | to whitelist this domain. 21 |
22 |
23 | ); 24 | } 25 | -------------------------------------------------------------------------------- /components/Upload.tsx: -------------------------------------------------------------------------------- 1 | import { useMemo, useState } from "react"; 2 | import { FileWithPath, useDropzone } from "react-dropzone"; 3 | 4 | const baseStyle = { 5 | flex: 1, 6 | display: "flex", 7 | flexDirection: "column", 8 | padding: "50px 20px", 9 | borderWidth: 2, 10 | borderRadius: 8, 11 | borderColor: "#d4d4d8", 12 | borderStyle: "dashed", 13 | color: "#3f3f46", 14 | outline: "none", 15 | transition: "border .24s ease-in-out", 16 | backgroundColor: "#fff", 17 | }; 18 | 19 | const focusedStyle = { 20 | borderColor: "#2196f3", 21 | }; 22 | 23 | const acceptStyle = { 24 | borderColor: "#71717a", 25 | }; 26 | 27 | const rejectStyle = { 28 | borderColor: "#ef4444", 29 | }; 30 | 31 | export type CustomFile = FileWithPath & { 32 | preview: string; 33 | }; 34 | 35 | type Props = { 36 | disabled?: boolean; 37 | onUpload: (file: File) => void; 38 | }; 39 | 40 | export default function Upload({ onUpload, disabled = false }: Props) { 41 | const [localFile, setLocalFile] = useState(); 42 | 43 | const { 44 | getRootProps, 45 | getInputProps, 46 | acceptedFiles, 47 | isFocused, 48 | isDragAccept, 49 | isDragReject, 50 | } = useDropzone({ 51 | accept: { "image/*": [] }, 52 | maxFiles: 1, 53 | disabled, 54 | onDrop: async (acceptedFiles) => { 55 | onUpload(acceptedFiles[0]); 56 | }, 57 | }); 58 | 59 | const style = useMemo( 60 | () => ({ 61 | ...baseStyle, 62 | ...(isFocused ? focusedStyle : {}), 63 | ...(isDragAccept ? acceptStyle : {}), 64 | ...(isDragReject ? rejectStyle : {}), 65 | }), 66 | [isFocused, isDragAccept, isDragReject] 67 | ); 68 | 69 | return ( 70 |
71 | 72 |

73 | Drop a image, or click to select one 74 |

75 |
76 | ); 77 | } 78 | -------------------------------------------------------------------------------- /components/UsageBar.tsx: -------------------------------------------------------------------------------- 1 | import { creditsAtom } from "@/atoms/atoms"; 2 | import { useAtomValue } from "jotai"; 3 | 4 | type Props = { 5 | showRatio?: boolean; 6 | }; 7 | 8 | export default function UsageBar({ showRatio = true }: Props) { 9 | const { used, limit } = useAtomValue(creditsAtom); 10 | 11 | return ( 12 |
13 |
14 |
20 | {`${ 21 | limit == 0 ? 0 : Math.ceil((used / limit) * 100) 22 | }%`} 23 |
24 |
25 | {showRatio && ( 26 |
27 |

28 | {used}/{limit} 29 |

30 |
31 | )} 32 |
33 | ); 34 | } 35 | -------------------------------------------------------------------------------- /components/layout/Container.tsx: -------------------------------------------------------------------------------- 1 | import { ReactNode } from "react"; 2 | 3 | export default function Container({ 4 | children, 5 | className, 6 | }: { 7 | children: ReactNode; 8 | className?: string; 9 | }) { 10 | return ( 11 |
12 | {children} 13 |
14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /components/layout/Footer.tsx: -------------------------------------------------------------------------------- 1 | import Link from "next/link"; 2 | import Container from "./Container"; 3 | 4 | export default function Footer() { 5 | return ( 6 |
7 | 8 |
9 |

10 | Powered by{" "} 11 | 17 | Rowy,{" "} 18 | 19 | 25 | Vercel,{" "} 26 | 27 | and{" "} 28 | 34 | Replicate 35 | 36 |

37 |
38 |
39 | 40 | 46 | 47 |
48 |
49 |
50 | ); 51 | } 52 | -------------------------------------------------------------------------------- /components/layout/Header.tsx: -------------------------------------------------------------------------------- 1 | import Link from "next/link"; 2 | import { registerOrLogin } from "@/lib/auth"; 3 | import { useAtomValue } from "jotai"; 4 | import { userAuthAtom } from "@/atoms/atoms"; 5 | import { Home2, PhotoEdit } from "tabler-icons-react"; 6 | 7 | import Dropdown from "../Dropdown"; 8 | import { useState } from "react"; 9 | import { FIREBASE_DOMAIN_ERROR } from "@/lib/const"; 10 | import UnauthorizedDomainError from "../UnauthorizedDomainError"; 11 | import Container from "./Container"; 12 | 13 | export default function Header() { 14 | const [errorCode, setErrorCode] = useState(); 15 | const { isAuthenticated } = useAtomValue(userAuthAtom); 16 | 17 | const handleLogin = async () => { 18 | const res = await registerOrLogin(); 19 | setErrorCode(res.errorCode); 20 | }; 21 | 22 | return ( 23 |
24 | 25 | {errorCode === FIREBASE_DOMAIN_ERROR && } 26 |
27 |
28 |
29 | 33 |

34 | background removal app. 35 |

36 | 37 | {isAuthenticated && ( 38 |
39 | 40 |
41 | )} 42 |
43 |
44 |
45 |
    46 | {!isAuthenticated && ( 47 | <> 48 |
  • 49 | 55 |
  • 56 |
  • 57 | 63 |
  • 64 | 65 | )} 66 | {isAuthenticated && ( 67 | <> 68 |
  • 69 | 70 | 74 | 75 |
  • 76 |
  • 77 | 78 | 82 | 83 | 84 | 88 | 89 |
  • 90 | 91 | )} 92 | {isAuthenticated && ( 93 |
  • 94 | 95 |
  • 96 | )} 97 |
98 |
99 |
100 |
101 |
102 | ); 103 | } 104 | -------------------------------------------------------------------------------- /components/layout/Layout.tsx: -------------------------------------------------------------------------------- 1 | import { ReactNode } from "react"; 2 | import Header from "./Header"; 3 | import Footer from "./Footer"; 4 | 5 | export default function Layout({ children }: { children: ReactNode }) { 6 | return ( 7 |
8 |
9 |
{children}
10 |
11 |
12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /lib/auth.ts: -------------------------------------------------------------------------------- 1 | import { auth } from "@/lib/firebase"; 2 | import { 3 | GoogleAuthProvider, 4 | signInWithPopup, 5 | User, 6 | signInAnonymously, 7 | } from "firebase/auth"; 8 | 9 | const provider = new GoogleAuthProvider(); 10 | 11 | export type FormattedUser = { 12 | uid: string; 13 | email: string | null; 14 | name: string | null; 15 | // provider: string; 16 | photoUrl: string | null; 17 | token: string; 18 | expirationTime: string; 19 | isAnonymous: boolean; 20 | }; 21 | 22 | export async function registerOrLogin(): Promise<{ 23 | errorCode?: string; 24 | errorMessage?: string; 25 | user?: FormattedUser; 26 | }> { 27 | try { 28 | const result = await signInWithPopup(auth, provider); 29 | 30 | // The signed-in user info. 31 | const user = result.user; 32 | 33 | const formattedUser = await formatUser(user); 34 | 35 | return { user: formattedUser }; 36 | } catch (error: any) { 37 | console.log("Failed to sign in", error); 38 | const errorCode = error.code; 39 | const errorMessage = error.message; 40 | // The AuthCredential type that was used. 41 | const credential = GoogleAuthProvider.credentialFromError(error); 42 | return { errorCode, errorMessage }; 43 | } 44 | } 45 | 46 | export async function anonymouslySignIn() { 47 | try { 48 | const result = await signInAnonymously(auth); 49 | 50 | // The signed-in user info. 51 | const user = result.user; 52 | 53 | const formattedUser = await formatUser(user); 54 | 55 | return { user: formattedUser }; 56 | } catch (error: any) { 57 | console.log("Anonymous sign in error:", error); 58 | const errorCode = error.code; 59 | const errorMessage = error.message; 60 | return { errorCode, errorMessage }; 61 | } 62 | } 63 | 64 | export const formatUser = async (user: User) => { 65 | const decodedToken = await user.getIdTokenResult(/*forceRefresh*/ true); 66 | const { token, expirationTime } = decodedToken; 67 | return { 68 | uid: user.uid, 69 | email: user.email, 70 | name: user.displayName, 71 | // provider: user.providerData.length 72 | // ? user.providerData[0].providerId 73 | // : user.providerId, 74 | photoUrl: user.photoURL, 75 | token, 76 | expirationTime, 77 | isAnonymous: user.isAnonymous, 78 | }; 79 | }; 80 | -------------------------------------------------------------------------------- /lib/const.ts: -------------------------------------------------------------------------------- 1 | export const FIREBASE_DOMAIN_ERROR = "auth/unauthorized-domain"; 2 | 3 | export const TABLE_ID = 4 | process.env.NEXT_PUBLIC_PROFILES_TABLE_ID || "microSaaSProfiles"; 5 | 6 | export const START_PREDICTION_ENDPOINT = process.env 7 | .NEXT_PUBLIC_START_PREDICTION_WEBHOOK as string; 8 | 9 | export const CREATE_STRIPE_CHECKOUT_ENDPOINT = process.env 10 | .NEXT_PUBLIC_CREATE_STRIPE_CHECKOUT_WEBHOOK as string; 11 | -------------------------------------------------------------------------------- /lib/download.ts: -------------------------------------------------------------------------------- 1 | function forceDownload(blobUrl: string, filename: string) { 2 | let a: any = document.createElement("a"); 3 | a.download = filename; 4 | a.href = blobUrl; 5 | document.body.appendChild(a); 6 | a.click(); 7 | a.remove(); 8 | } 9 | 10 | export default function downloadPhoto(url: string, filename: string) { 11 | fetch(url, { 12 | headers: new Headers({ 13 | Origin: location.origin, 14 | }), 15 | mode: "cors", 16 | }) 17 | .then((response) => response.blob()) 18 | .then((blob) => { 19 | let blobUrl = window.URL.createObjectURL(blob); 20 | forceDownload(blobUrl, filename); 21 | }) 22 | .catch((e) => console.error(e)); 23 | } 24 | 25 | export function appendNewToName(name: string) { 26 | let insertPos = name.indexOf("."); 27 | let newName = name 28 | .substring(0, insertPos) 29 | .concat("-new", name.substring(insertPos)); 30 | return newName; 31 | } 32 | -------------------------------------------------------------------------------- /lib/firebase.ts: -------------------------------------------------------------------------------- 1 | import { initializeApp } from "firebase/app"; 2 | import { getAuth } from "firebase/auth"; 3 | import { getFirestore } from "firebase/firestore"; 4 | import { getStorage } from "firebase/storage"; 5 | 6 | const firebaseConfig = { 7 | apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, 8 | authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, 9 | projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, 10 | storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, 11 | messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_SENDER_ID, 12 | appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, 13 | }; 14 | 15 | // Initialize Firebase 16 | const app = initializeApp(firebaseConfig); 17 | 18 | export const auth = getAuth(app); 19 | export const db = getFirestore(app); 20 | export const storage = getStorage(app); 21 | 22 | export default app; 23 | -------------------------------------------------------------------------------- /lib/get-schema.ts: -------------------------------------------------------------------------------- 1 | import { doc, getDoc } from "firebase/firestore"; 2 | import { db } from "./firebase"; 3 | import { TABLE_ID } from "./const"; 4 | 5 | type TableEnv = { 6 | tableEnv: { 7 | collectionIds: Record; 8 | }; 9 | }; 10 | 11 | export async function getSchema() { 12 | const schemaRef = doc(db, `_rowy_/settings/schema/${TABLE_ID}`); 13 | const schema = await getDoc(schemaRef); 14 | return schema.data() as TableEnv; 15 | } 16 | -------------------------------------------------------------------------------- /lib/packages.ts: -------------------------------------------------------------------------------- 1 | import { db } from "@/lib/firebase"; 2 | import { doc, DocumentData, getDoc, getDocs, Query } from "firebase/firestore"; 3 | import { getSchema } from "./get-schema"; 4 | 5 | export async function getPackage(id: string) { 6 | const { tableEnv } = await getSchema(); 7 | 8 | const packagesRef = doc(db, tableEnv.collectionIds["microSaaSPackages"], id); 9 | const packagesSnap = await getDoc(packagesRef); 10 | 11 | if (packagesSnap.exists()) { 12 | const data = packagesSnap.data(); 13 | return data; 14 | } 15 | } 16 | 17 | export async function getPackages(q: Query) { 18 | const packagesSnapshot = await getDocs(q); 19 | return packagesSnapshot.docs; 20 | } 21 | -------------------------------------------------------------------------------- /lib/profiles.ts: -------------------------------------------------------------------------------- 1 | import { db } from "@/lib/firebase"; 2 | import { 3 | collection, 4 | doc, 5 | getDocs, 6 | query, 7 | setDoc, 8 | where, 9 | } from "firebase/firestore"; 10 | import { getSchema } from "./get-schema"; 11 | 12 | export async function getUserProfile(userId: string) { 13 | const { tableEnv } = await getSchema(); 14 | const profilesQuery = query( 15 | collection(db, tableEnv.collectionIds["microSaaSProfiles"]), 16 | where("userId", "==", userId) 17 | ); 18 | const profilesSnapshot = await getDocs(profilesQuery); 19 | 20 | if (!profilesSnapshot.empty) { 21 | const profile = profilesSnapshot.docs[0]; 22 | return profile; 23 | } 24 | } 25 | 26 | export async function getOrCreateProfile(userId: string, isAnonymous: boolean) { 27 | const { tableEnv } = await getSchema(); 28 | const existingProfile = await getUserProfile(userId); 29 | if (!existingProfile) { 30 | const profilesRef = collection( 31 | db, 32 | tableEnv.collectionIds["microSaaSProfiles"] 33 | ); 34 | if (!isAnonymous) { 35 | // Assign free package for new users 36 | await setDoc(doc(profilesRef), { 37 | userId, 38 | isAnonymous: false, 39 | package: { 40 | limit: 100, 41 | used: 0, 42 | }, 43 | "_createdBy.timestamp": new Date(), 44 | }); 45 | } else { 46 | await setDoc(doc(profilesRef), { 47 | userId, 48 | isAnonymous: true, 49 | package: { 50 | limit: 10, 51 | used: 0, 52 | }, 53 | "_createdBy.timestamp": new Date(), 54 | }); 55 | } 56 | } 57 | 58 | return await getUserProfile(userId); 59 | } 60 | -------------------------------------------------------------------------------- /lib/storage.ts: -------------------------------------------------------------------------------- 1 | import { 2 | getDownloadURL, 3 | StorageReference, 4 | uploadBytes, 5 | } from "firebase/storage"; 6 | 7 | export async function upload(storageRef: StorageReference, file: File | Blob) { 8 | try { 9 | const snapshot = await uploadBytes(storageRef, file); 10 | const downloadURL = await getDownloadURL(snapshot.ref); 11 | return downloadURL; 12 | } catch (error) { 13 | console.log("Storage error", error); 14 | throw error; 15 | } 16 | } 17 | 18 | export function getImageExtension(imageUrl: string) { 19 | const extension = imageUrl.split(".").pop()?.toLowerCase(); 20 | if (extension === "jpg") { 21 | return "jpeg"; 22 | } 23 | return extension || undefined; 24 | } 25 | -------------------------------------------------------------------------------- /lib/types.ts: -------------------------------------------------------------------------------- 1 | export type Profile = { 2 | id: string; 3 | userId: string; 4 | token: string; 5 | expirationTime: string; 6 | isAnonymous: boolean; 7 | photoUrl?: string | null; 8 | }; 9 | 10 | export type Package = { 11 | id: string; 12 | limit: number; 13 | price: number; 14 | }; 15 | 16 | export type Prediction = { 17 | id: string; 18 | input: string; 19 | output: string; 20 | }; 21 | 22 | export type ProfilePackage = { 23 | used: number; 24 | limit: number; 25 | }; 26 | 27 | export type Credits = { 28 | used: number; 29 | limit: number; 30 | }; 31 | 32 | export type Auth = { 33 | user?: Profile; 34 | isAuthenticated: boolean; 35 | }; 36 | -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = { 3 | reactStrictMode: true, 4 | images: { 5 | domains: [ 6 | `${process.env.S3_UPLOAD_BUCKET}.s3.amazonaws.com`, 7 | `${process.env.S3_UPLOAD_BUCKET}.s3.${process.env.S3_UPLOAD_REGION}.amazonaws.com`, 8 | "replicate.delivery", 9 | "firebasestorage.googleapis.com", 10 | "lh3.googleusercontent.com", 11 | ], 12 | }, 13 | }; 14 | 15 | module.exports = nextConfig; 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bg-removal-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint" 10 | }, 11 | "dependencies": { 12 | "@next/font": "13.2.1", 13 | "@types/node": "18.14.2", 14 | "@types/react": "18.0.28", 15 | "@types/react-dom": "18.0.11", 16 | "classnames": "^2.3.2", 17 | "eslint": "8.35.0", 18 | "eslint-config-next": "13.2.1", 19 | "firebase": "^9.17.1", 20 | "jotai": "^2.0.2", 21 | "next": "13.2.1", 22 | "react": "18.2.0", 23 | "react-dom": "18.2.0", 24 | "react-dom-confetti": "^0.2.0", 25 | "react-dropzone": "^14.2.3", 26 | "react-hot-toast": "^2.4.0", 27 | "react-modal": "^3.16.1", 28 | "stripe": "^11.12.0", 29 | "tabler-icons-react": "^1.56.0", 30 | "typescript": "4.9.5", 31 | "uuid": "^9.0.0" 32 | }, 33 | "devDependencies": { 34 | "@types/react-modal": "^3.13.1", 35 | "@types/uuid": "^9.0.1", 36 | "autoprefixer": "^10.4.13", 37 | "postcss": "^8.4.21", 38 | "prettier": "^2.8.4", 39 | "prettier-plugin-tailwindcss": "^0.2.3", 40 | "tailwindcss": "^3.2.7" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import Layout from "@/components/layout/Layout"; 2 | import "@/styles/globals.css"; 3 | import type { AppProps } from "next/app"; 4 | import { Toaster } from "react-hot-toast"; 5 | import { Inter } from "@next/font/google"; 6 | import localFont from "next/font/local"; 7 | import cx from "classnames"; 8 | import AuthIsLoaded from "@/components/AuthIsLoaded"; 9 | 10 | const satoshi = localFont({ 11 | src: "../styles/Satoshi-Variable.woff2", 12 | variable: "--font-satoshi", 13 | weight: "300 900", 14 | display: "swap", 15 | style: "normal", 16 | }); 17 | 18 | const inter = Inter({ 19 | variable: "--font-inter", 20 | subsets: ["latin"], 21 | }); 22 | 23 | export default function App({ Component, pageProps }: AppProps) { 24 | return ( 25 | 26 |
27 | 28 | 29 | 30 | 31 | 32 |
33 |
34 | ); 35 | } 36 | -------------------------------------------------------------------------------- /pages/_document.tsx: -------------------------------------------------------------------------------- 1 | import { Html, Head, Main, NextScript } from "next/document"; 2 | 3 | export default function Document() { 4 | return ( 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /pages/dashboard.tsx: -------------------------------------------------------------------------------- 1 | import { userAuthAtom } from "@/atoms/atoms"; 2 | import Hero from "@/components/Hero"; 3 | import Container from "@/components/layout/Container"; 4 | import downloadPhoto, { appendNewToName } from "@/lib/download"; 5 | import { db } from "@/lib/firebase"; 6 | import { getSchema } from "@/lib/get-schema"; 7 | import { Prediction, Profile } from "@/lib/types"; 8 | import { collection, getDocs, query } from "firebase/firestore"; 9 | import { useAtomValue } from "jotai"; 10 | import Head from "next/head"; 11 | import Image from "next/image"; 12 | import { useRouter } from "next/router"; 13 | import { useEffect, useState } from "react"; 14 | import { Download } from "tabler-icons-react"; 15 | 16 | export default function Dashboard() { 17 | const { isAuthenticated, user } = useAtomValue(userAuthAtom); 18 | const [images, setImages] = useState([]); 19 | const router = useRouter(); 20 | 21 | useEffect(() => { 22 | if (user && !isAuthenticated) router.push("/"); 23 | }, [router, isAuthenticated, user]); 24 | 25 | useEffect(() => { 26 | const loadImages = async (user: Profile) => { 27 | const { tableEnv } = await getSchema(); 28 | 29 | const imagesQuery = query( 30 | collection( 31 | db, 32 | tableEnv.collectionIds["microSaaSProfiles"], 33 | user.id, 34 | "images" 35 | ) 36 | ); 37 | const imagesSnap = await getDocs(imagesQuery); 38 | 39 | if (!imagesSnap.empty) { 40 | const images: Prediction[] = imagesSnap.docs.map((doc) => ({ 41 | id: doc.id, 42 | input: doc.data().input, 43 | output: doc.data().output, 44 | })); 45 | setImages(images); 46 | } 47 | }; 48 | if (user) loadImages(user); 49 | }, [user]); 50 | 51 | return ( 52 | <> 53 | 54 | Dashboard 55 | 56 | 57 | 58 |
59 |
60 | 64 |
65 |
66 | 67 |
68 | {images.length > 0 && ( 69 |
    70 | {images.map((image, index) => ( 71 |
  • 75 |
    76 | input 83 | 94 |
    95 |
    96 | output 103 | 114 |
    115 |
  • 116 | ))} 117 |
118 | )} 119 |
120 |
121 | 122 | ); 123 | } 124 | -------------------------------------------------------------------------------- /pages/index.tsx: -------------------------------------------------------------------------------- 1 | import { userAuthAtom } from "@/atoms/atoms"; 2 | import Hero from "@/components/Hero"; 3 | import Container from "@/components/layout/Container"; 4 | import { useAtomValue } from "jotai"; 5 | import Head from "next/head"; 6 | import Image from "next/image"; 7 | import Link from "next/link"; 8 | 9 | export default function Home() { 10 | const { isAuthenticated } = useAtomValue(userAuthAtom); 11 | return ( 12 | <> 13 | 14 | Background Removal App 15 | 16 | 17 | 18 |
19 |
20 | 21 |
22 |
23 |

Powered by

24 |
25 |
26 | rowy logo 32 |
33 |
34 | 35 |
36 | 48 |
49 |
50 |
51 |
52 |
53 |

54 | Original photo 55 |

56 | Original photo of me 63 |
64 |
65 |

66 | Background removed 67 |

68 | Restored photo of me 75 |
76 |
77 |
78 |
79 | 80 |
81 |

82 | 83 | Want to know what it takes to build an app like this? 84 | 85 |

86 |

87 | 🍿 Check out the{" "} 88 | 93 | video tutorial 94 | 95 |

96 |
97 |
98 | 99 | ); 100 | } 101 | -------------------------------------------------------------------------------- /pages/packages.tsx: -------------------------------------------------------------------------------- 1 | import { creditsAtom, userAuthAtom } from "@/atoms/atoms"; 2 | import Hero from "@/components/Hero"; 3 | import Packages from "@/components/Packages"; 4 | import UsageBar from "@/components/UsageBar"; 5 | import Container from "@/components/layout/Container"; 6 | import { useAtomValue } from "jotai"; 7 | import Head from "next/head"; 8 | import { useRouter } from "next/router"; 9 | import { useEffect } from "react"; 10 | import { toast } from "react-hot-toast"; 11 | import Confetti from "react-dom-confetti"; 12 | 13 | export default function BuyCredits() { 14 | const { isAuthenticated, user } = useAtomValue(userAuthAtom); 15 | const { used, limit } = useAtomValue(creditsAtom); 16 | const router = useRouter(); 17 | 18 | const { payment_status: paymentStatus } = router.query; 19 | 20 | useEffect(() => { 21 | if (user && !isAuthenticated) router.push("/"); 22 | }, [router, isAuthenticated, user]); 23 | 24 | useEffect(() => { 25 | if (paymentStatus && paymentStatus === "success") { 26 | toast.success("Purchase successful"); 27 | } 28 | if (paymentStatus && paymentStatus === "cancel") { 29 | toast.error("Purchase cancelled"); 30 | } 31 | }, [paymentStatus]); 32 | 33 | return ( 34 | <> 35 | 36 | Packages 37 | 38 | 39 | 40 |
41 |
42 | 46 |
47 | 48 |
49 |
50 | 54 |
55 | 56 |
57 |
58 |

59 | Your usage 60 |

61 |
62 | {used != undefined && limit != undefined && ( 63 |
64 |

65 | Used: {used}/{limit} 66 |

67 |
68 | )} 69 |
70 | 71 |
72 |
73 |
74 |

75 | Simple,{" "} 76 | 77 | credit-based 78 | {" "} 79 | packages 80 |

81 |
82 |

Note: 1 credit = 1 photo

83 |
84 |
85 | 86 |
87 |
88 |
89 | 90 | ); 91 | } 92 | -------------------------------------------------------------------------------- /pages/remove.tsx: -------------------------------------------------------------------------------- 1 | import Head from "next/head"; 2 | import { useEffect, useState } from "react"; 3 | import Image from "next/image"; 4 | import Upload, { CustomFile } from "@/components/Upload"; 5 | import Modal from "@/components/Modal"; 6 | import { db, storage } from "@/lib/firebase"; 7 | import { registerOrLogin } from "@/lib/auth"; 8 | import Link from "next/link"; 9 | import UsageBar from "@/components/UsageBar"; 10 | import Hero from "@/components/Hero"; 11 | import Spinner from "@/components/Spinner"; 12 | import downloadPhoto, { appendNewToName } from "@/lib/download"; 13 | import { useRouter } from "next/router"; 14 | import { ref } from "firebase/storage"; 15 | import { v4 as uuidv4 } from "uuid"; 16 | import { upload } from "@/lib/storage"; 17 | import { doc, onSnapshot } from "firebase/firestore"; 18 | import { useAtomValue } from "jotai"; 19 | import { creditsAtom, userAuthAtom } from "@/atoms/atoms"; 20 | import Container from "@/components/layout/Container"; 21 | import { getSchema } from "@/lib/get-schema"; 22 | import { START_PREDICTION_ENDPOINT } from "@/lib/const"; 23 | 24 | export default function RemoveBackground() { 25 | const [localFile, setLocalFile] = useState(); 26 | const [prediction, setPrediction] = useState(null); 27 | const [error, setError] = useState(null); 28 | const [loading, setLoading] = useState(false); 29 | const [removedBgLoaded, setRemovedBgLoaded] = useState(false); 30 | const [showLoginModal, setShowLoginModal] = useState(false); 31 | const [photoName, setPhotoName] = useState(null); 32 | const [predictionId, setPredictionId] = useState(); 33 | const [output, setOutput] = useState(); 34 | 35 | const { user, isAuthenticated } = useAtomValue(userAuthAtom); 36 | const { used, limit } = useAtomValue(creditsAtom); 37 | const router = useRouter(); 38 | 39 | const handleUpload = async (file: File) => { 40 | if (used >= limit) { 41 | setShowLoginModal(true); 42 | return; 43 | } 44 | 45 | setLoading(true); 46 | setPhotoName(file.name); 47 | setLocalFile( 48 | Object.assign(file, { 49 | preview: URL.createObjectURL(file), 50 | }) 51 | ); 52 | 53 | const storageRef = ref(storage, `images/${uuidv4()}/${file.name}`); 54 | 55 | const uploadedImageUrl = await upload(storageRef, file); 56 | 57 | const { tableEnv } = await getSchema(); 58 | 59 | const response = await fetch(START_PREDICTION_ENDPOINT, { 60 | method: "POST", 61 | headers: { 62 | "Content-Type": "application/json", 63 | token: `${user?.token}`, 64 | }, 65 | body: JSON.stringify({ 66 | image: uploadedImageUrl, 67 | profileId: user?.id, 68 | }), 69 | }); 70 | 71 | const prediction = await response.json(); 72 | 73 | if (response.status !== 200) { 74 | console.log("prediction error", prediction.detail); 75 | setError(prediction.detail); 76 | setLoading(false); 77 | return; 78 | } 79 | 80 | if (prediction.predictionId) { 81 | setPredictionId(prediction.predictionId as string); 82 | return; 83 | } 84 | }; 85 | 86 | // Listen for when the prediction is completed 87 | useEffect(() => { 88 | async function onPredictionComplete() { 89 | const { tableEnv } = await getSchema(); 90 | if (predictionId) { 91 | const unsub = onSnapshot( 92 | doc( 93 | db, 94 | `${tableEnv.collectionIds["microSaaSProfiles"]}/${user?.id}/images/${predictionId}` 95 | ), 96 | (doc) => { 97 | const prediction = doc.data(); 98 | if (prediction && prediction.output) { 99 | setOutput(prediction.output); 100 | setLoading(false); 101 | } 102 | } 103 | ); 104 | return () => { 105 | unsub(); 106 | }; 107 | } 108 | } 109 | onPredictionComplete(); 110 | }, [predictionId]); 111 | 112 | useEffect(() => { 113 | // Make sure to revoke the data uris to avoid memory leaks, will run on unmount 114 | return () => localFile && URL.revokeObjectURL(localFile.preview); 115 | }, []); 116 | 117 | return ( 118 | <> 119 | 120 | Remove Background 121 | 122 | 123 | 124 | 125 |
126 | 130 |
131 | 132 | 133 |
134 |
135 |
136 |
137 | 1 138 |
139 |

Upload

140 |
141 | 142 | {localFile && ( 143 | uploaded photo 150 | )} 151 | 152 | {!removedBgLoaded && } 153 | 154 | {removedBgLoaded && ( 155 |
156 | 169 |
170 | )} 171 | 172 |
173 | 174 |
175 |
176 |
177 |
178 |
179 | 2 180 |
181 |

Result

182 |
183 | 184 | {error && ( 185 |

186 | An error occurred, please try again later. 187 |

188 | )} 189 | 190 | {loading && ( 191 |
192 | 193 |
194 | )} 195 | 196 | {output && ( 197 |
198 | {!removedBgLoaded && ( 199 |
200 | 201 |

202 | Adding final touches... 203 |

204 |
205 | )} 206 | output setRemovedBgLoaded(true)} 213 | /> 214 |
215 | )} 216 | 217 | {removedBgLoaded && output && ( 218 |
219 | 227 |
228 | )} 229 |
230 |
231 |
232 | 233 | setShowLoginModal(false)} 236 | title={user ? "Credit limit reached" : "Sign in to continue"} 237 | > 238 |
239 |
240 |

Oh oh, you've used up all your credits.

241 | {!user && ( 242 |

243 | Good news is by signing up you get an additional 100 free 244 | credits! 245 |

246 | )} 247 | {user && ( 248 |

You will need to purchase additional credits to continue.

249 | )} 250 |
251 | 252 |
253 | {!isAuthenticated && ( 254 | 265 | )} 266 | {isAuthenticated && ( 267 | 268 | 271 | 272 | )} 273 |
274 |
275 |
276 | 277 | ); 278 | } 279 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /public/avatar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/public/avatar.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/public/favicon.ico -------------------------------------------------------------------------------- /public/input.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/public/input.jpeg -------------------------------------------------------------------------------- /public/next.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/output.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/public/output.jpeg -------------------------------------------------------------------------------- /public/photo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /public/rowy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/public/rowy.png -------------------------------------------------------------------------------- /public/screenshot.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/public/screenshot.jpeg -------------------------------------------------------------------------------- /public/thirteen.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/vercel.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /styles/Satoshi-Black.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/styles/Satoshi-Black.ttf -------------------------------------------------------------------------------- /styles/Satoshi-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/styles/Satoshi-Bold.ttf -------------------------------------------------------------------------------- /styles/Satoshi-Variable.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/demo-microsaas/ab67fd5ed3c5e5a30a990e171d08469f9e78c2ef/styles/Satoshi-Variable.woff2 -------------------------------------------------------------------------------- /styles/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | 6 | body.fullscreen-active { 7 | overflow: hidden; 8 | } -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('tailwindcss').Config} */ 2 | module.exports = { 3 | content: [ 4 | "./app/**/*.{js,ts,jsx,tsx}", 5 | "./pages/**/*.{js,ts,jsx,tsx}", 6 | "./components/**/*.{js,ts,jsx,tsx}", 7 | 8 | // Or if using `src` directory: 9 | "./src/**/*.{js,ts,jsx,tsx}", 10 | ], 11 | theme: { 12 | extend: { 13 | fontFamily: { 14 | display: ["var(--font-satoshi)", "system-ui", "sans-serif"], 15 | default: ["var(--font-inter)", "system-ui", "sans-serif"], 16 | }, 17 | }, 18 | }, 19 | plugins: [], 20 | }; 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true, 17 | "baseUrl": ".", 18 | "paths": { 19 | "@/*": ["./*"] 20 | } 21 | }, 22 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], 23 | "exclude": ["node_modules"] 24 | } 25 | --------------------------------------------------------------------------------