├── supabase ├── seed.sql ├── .gitignore └── config.toml ├── components ├── ui │ ├── Input │ │ ├── index.ts │ │ ├── Input.module.css │ │ └── Input.tsx │ ├── Navbar │ │ ├── index.ts │ │ ├── Navbar.module.css │ │ └── Navbar.tsx │ ├── Button │ │ ├── index.ts │ │ ├── Button.module.css │ │ └── Button.tsx │ ├── Footer │ │ ├── index.ts │ │ └── Footer.tsx │ └── LoadingDots │ │ ├── index.ts │ │ ├── LoadingDots.tsx │ │ └── LoadingDots.module.css ├── icons │ ├── Logo.tsx │ └── GitHub.tsx ├── Layout.tsx └── Pricing.tsx ├── public ├── og.png ├── demo.png ├── favicon.ico ├── vercel-deploy.png ├── stripe.svg ├── vercel.svg ├── github.svg ├── nextjs.svg ├── supabase.svg └── architecture_diagram.svg ├── postcss.config.js ├── next.config.js ├── next-env.d.ts ├── styles ├── chrome-bug.css └── main.css ├── pages ├── _document.tsx ├── index.tsx ├── _app.tsx ├── api │ ├── create-portal-link.ts │ ├── create-checkout-session.ts │ └── webhooks.ts ├── signin.tsx └── account.tsx ├── .env.local.example ├── utils ├── stripe-client.ts ├── stripe.ts ├── supabase-client.ts ├── helpers.ts ├── useUser.tsx └── supabase-admin.ts ├── tailwind.config.js ├── .gitignore ├── tsconfig.json ├── LICENSE ├── package.json ├── types.ts ├── fixtures └── stripe-fixtures.json ├── schema.sql ├── README.md ├── types_db.ts └── pnpm-lock.yaml /supabase/seed.sql: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /supabase/.gitignore: -------------------------------------------------------------------------------- 1 | # Supabase 2 | .branches 3 | .temp 4 | -------------------------------------------------------------------------------- /components/ui/Input/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Input'; 2 | -------------------------------------------------------------------------------- /components/ui/Navbar/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Navbar' 2 | -------------------------------------------------------------------------------- /components/ui/Button/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Button'; 2 | -------------------------------------------------------------------------------- /components/ui/Footer/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Footer'; 2 | -------------------------------------------------------------------------------- /components/ui/LoadingDots/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './LoadingDots'; 2 | -------------------------------------------------------------------------------- /public/og.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/nextjs-subscription-payments/HEAD/public/og.png -------------------------------------------------------------------------------- /public/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/nextjs-subscription-payments/HEAD/public/demo.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/nextjs-subscription-payments/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = { 3 | plugins: { 4 | tailwindcss: {}, 5 | autoprefixer: {} 6 | } 7 | }; -------------------------------------------------------------------------------- /public/vercel-deploy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanveerpot/nextjs-subscription-payments/HEAD/public/vercel-deploy.png -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = { 3 | reactStrictMode: true, 4 | }; 5 | 6 | module.exports = nextConfig; 7 | -------------------------------------------------------------------------------- /next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | // NOTE: This file should not be edited 5 | // see https://nextjs.org/docs/basic-features/typescript for more information. 6 | -------------------------------------------------------------------------------- /components/ui/Input/Input.module.css: -------------------------------------------------------------------------------- 1 | .root { 2 | @apply bg-black py-2 px-3 w-full appearance-none transition duration-150 ease-in-out border border-zinc-500 text-zinc-200; 3 | } 4 | 5 | .root:focus { 6 | @apply outline-none; 7 | } 8 | -------------------------------------------------------------------------------- /components/ui/LoadingDots/LoadingDots.tsx: -------------------------------------------------------------------------------- 1 | import s from './LoadingDots.module.css'; 2 | 3 | const LoadingDots = () => { 4 | return ( 5 | 6 | 7 | 8 | 9 | 10 | ); 11 | }; 12 | 13 | export default LoadingDots; 14 | -------------------------------------------------------------------------------- /styles/chrome-bug.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Chrome has a bug with transitions on load since 2012! 3 | * 4 | * To prevent a "pop" of content, you have to disable all transitions until 5 | * the page is done loading. 6 | * 7 | * https://lab.laukstein.com/bug/input 8 | * https://twitter.com/timer150/status/1345217126680899584 9 | */ 10 | body.loading * { 11 | transition: none !important; 12 | } 13 | -------------------------------------------------------------------------------- /pages/_document.tsx: -------------------------------------------------------------------------------- 1 | import Document, { Head, Html, Main, NextScript } from 'next/document'; 2 | 3 | class MyDocument extends Document { 4 | render() { 5 | return ( 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | ); 14 | } 15 | } 16 | 17 | export default MyDocument; 18 | -------------------------------------------------------------------------------- /.env.local.example: -------------------------------------------------------------------------------- 1 | # Update these with your Supabase details from your project settings > API 2 | NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co 3 | NEXT_PUBLIC_SUPABASE_ANON_KEY= 4 | SUPABASE_SERVICE_ROLE_KEY= 5 | 6 | # Update these with your Stripe credentials from https://dashboard.stripe.com/apikeys 7 | NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_1234 8 | STRIPE_SECRET_KEY=sk_test_1234 9 | STRIPE_WEBHOOK_SECRET=whsec_1234 -------------------------------------------------------------------------------- /utils/stripe-client.ts: -------------------------------------------------------------------------------- 1 | import { loadStripe, Stripe } from '@stripe/stripe-js'; 2 | 3 | let stripePromise: Promise; 4 | 5 | export const getStripe = () => { 6 | if (!stripePromise) { 7 | stripePromise = loadStripe( 8 | process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY_LIVE ?? 9 | process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? 10 | '' 11 | ); 12 | } 13 | 14 | return stripePromise; 15 | }; 16 | -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | const { fontFamily } = require('tailwindcss/defaultTheme'); 2 | 3 | /** @type {import('tailwindcss').Config} */ 4 | module.exports = { 5 | darkMode: ['class', '[data-theme="dark"]'], 6 | content: [ 7 | 'app/**/*.{ts,tsx}', 8 | 'components/**/*.{ts,tsx}', 9 | 'pages/**/*.{ts,tsx}' 10 | ], 11 | theme: { 12 | extend: { 13 | fontFamily: { 14 | sans: ['var(--font-sans)', ...fontFamily.sans] 15 | } 16 | } 17 | }, 18 | plugins: [] 19 | }; 20 | -------------------------------------------------------------------------------- /utils/stripe.ts: -------------------------------------------------------------------------------- 1 | import Stripe from 'stripe'; 2 | 3 | export const stripe = new Stripe( 4 | process.env.STRIPE_SECRET_KEY_LIVE ?? process.env.STRIPE_SECRET_KEY ?? '', 5 | { 6 | // https://github.com/stripe/stripe-node#configuration 7 | apiVersion: '2022-11-15', 8 | // Register this as an official Stripe plugin. 9 | // https://stripe.com/docs/building-plugins#setappinfo 10 | appInfo: { 11 | name: 'Next.js Subscription Starter', 12 | version: '0.1.0' 13 | } 14 | } 15 | ); 16 | -------------------------------------------------------------------------------- /components/ui/Navbar/Navbar.module.css: -------------------------------------------------------------------------------- 1 | .root { 2 | @apply sticky top-0 bg-black z-40 transition-all duration-150; 3 | } 4 | 5 | .link { 6 | @apply inline-flex items-center leading-6 font-medium transition ease-in-out duration-75 cursor-pointer text-zinc-200 rounded-md p-1; 7 | } 8 | 9 | .link:hover { 10 | @apply text-zinc-100; 11 | } 12 | 13 | .link:focus { 14 | @apply outline-none text-zinc-100 ring-2 ring-pink-500 ring-opacity-50; 15 | } 16 | 17 | .logo { 18 | @apply cursor-pointer rounded-full transform duration-100 ease-in-out; 19 | } 20 | -------------------------------------------------------------------------------- /.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 | 27 | # local env files 28 | .env.local 29 | .env.development.local 30 | .env.test.local 31 | .env.production.local 32 | 33 | # vercel 34 | .vercel 35 | 36 | # editors 37 | .vscode 38 | -------------------------------------------------------------------------------- /pages/index.tsx: -------------------------------------------------------------------------------- 1 | import { GetStaticPropsResult } from 'next'; 2 | 3 | import Pricing from '@/components/Pricing'; 4 | import { getActiveProductsWithPrices } from '@/utils/supabase-client'; 5 | import { Product } from 'types'; 6 | 7 | interface Props { 8 | products: Product[]; 9 | } 10 | 11 | export default function PricingPage({ products }: Props) { 12 | return ; 13 | } 14 | 15 | export async function getStaticProps(): Promise> { 16 | const products = await getActiveProductsWithPrices(); 17 | 18 | return { 19 | props: { 20 | products 21 | }, 22 | revalidate: 60 23 | }; 24 | } 25 | -------------------------------------------------------------------------------- /components/ui/LoadingDots/LoadingDots.module.css: -------------------------------------------------------------------------------- 1 | .root { 2 | @apply inline-flex text-center items-center leading-7; 3 | } 4 | 5 | .root span { 6 | @apply bg-zinc-200 rounded-full h-2 w-2; 7 | animation-name: blink; 8 | animation-duration: 1.4s; 9 | animation-iteration-count: infinite; 10 | animation-fill-mode: both; 11 | margin: 0 2px; 12 | } 13 | 14 | .root span:nth-of-type(2) { 15 | animation-delay: 0.2s; 16 | } 17 | 18 | .root span:nth-of-type(3) { 19 | animation-delay: 0.4s; 20 | } 21 | 22 | @keyframes blink { 23 | 0% { 24 | opacity: 0.2; 25 | } 26 | 20% { 27 | opacity: 1; 28 | } 29 | 100% { 30 | opacity: 0.2; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /components/icons/Logo.tsx: -------------------------------------------------------------------------------- 1 | const Logo = ({ className = '', ...props }) => ( 2 | 11 | 12 | 18 | 19 | ); 20 | 21 | export default Logo; 22 | -------------------------------------------------------------------------------- /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 | "baseUrl": ".", 17 | "paths": { 18 | "@/*": ["./*"] 19 | }, 20 | "incremental": true 21 | }, 22 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], 23 | "exclude": ["node_modules"] 24 | } 25 | -------------------------------------------------------------------------------- /components/ui/Button/Button.module.css: -------------------------------------------------------------------------------- 1 | .root { 2 | @apply bg-white text-zinc-800 cursor-pointer inline-flex px-10 rounded-sm leading-6 transition ease-in-out duration-150 shadow-sm font-semibold text-center justify-center uppercase py-4 border border-transparent items-center; 3 | } 4 | 5 | .root:hover { 6 | @apply bg-zinc-800 text-white border border-white; 7 | } 8 | 9 | .root:focus { 10 | @apply outline-none ring-2 ring-pink-500 ring-opacity-50; 11 | } 12 | 13 | .root[data-active] { 14 | @apply bg-zinc-600; 15 | } 16 | 17 | .loading { 18 | @apply bg-zinc-700 text-zinc-500 border-zinc-600 cursor-not-allowed; 19 | } 20 | 21 | .slim { 22 | @apply py-2 transform-none normal-case; 23 | } 24 | 25 | .disabled, 26 | .disabled:hover { 27 | @apply text-zinc-400 border-zinc-600 bg-zinc-700 cursor-not-allowed; 28 | filter: grayscale(1); 29 | -webkit-transform: translateZ(0); 30 | -webkit-perspective: 1000; 31 | -webkit-backface-visibility: hidden; 32 | } 33 | -------------------------------------------------------------------------------- /components/ui/Input/Input.tsx: -------------------------------------------------------------------------------- 1 | import React, { InputHTMLAttributes, ChangeEvent } from 'react'; 2 | import cn from 'classnames'; 3 | 4 | import s from './Input.module.css'; 5 | 6 | interface Props extends Omit, 'onChange'> { 7 | className?: string; 8 | onChange: (value: string) => void; 9 | } 10 | const Input = (props: Props) => { 11 | const { className, children, onChange, ...rest } = props; 12 | 13 | const rootClassName = cn(s.root, {}, className); 14 | 15 | const handleOnChange = (e: ChangeEvent) => { 16 | if (onChange) { 17 | onChange(e.target.value); 18 | } 19 | return null; 20 | }; 21 | 22 | return ( 23 | 34 | ); 35 | }; 36 | 37 | export default Input; 38 | -------------------------------------------------------------------------------- /utils/supabase-client.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createBrowserSupabaseClient, 3 | User 4 | } from '@supabase/auth-helpers-nextjs'; 5 | 6 | import { ProductWithPrice } from 'types'; 7 | import type { Database } from 'types_db'; 8 | 9 | export const supabase = createBrowserSupabaseClient(); 10 | 11 | export const getActiveProductsWithPrices = async (): Promise< 12 | ProductWithPrice[] 13 | > => { 14 | const { data, error } = await supabase 15 | .from('products') 16 | .select('*, prices(*)') 17 | .eq('active', true) 18 | .eq('prices.active', true) 19 | .order('metadata->index') 20 | .order('unit_amount', { foreignTable: 'prices' }); 21 | 22 | if (error) { 23 | console.log(error.message); 24 | } 25 | // TODO: improve the typing here. 26 | return (data as any) || []; 27 | }; 28 | 29 | export const updateUserName = async (user: User, name: string) => { 30 | await supabase 31 | .from('users') 32 | .update({ 33 | full_name: name 34 | }) 35 | .eq('id', user.id); 36 | }; 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Vercel, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from 'react'; 2 | import React from 'react'; 3 | import { AppProps } from 'next/app'; 4 | import { SessionContextProvider } from '@supabase/auth-helpers-react'; 5 | import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'; 6 | 7 | import Layout from '@/components/Layout'; 8 | import { MyUserContextProvider } from '@/utils/useUser'; 9 | import type { Database } from 'types_db'; 10 | 11 | import 'styles/main.css'; 12 | import 'styles/chrome-bug.css'; 13 | 14 | export default function MyApp({ Component, pageProps }: AppProps) { 15 | const [supabaseClient] = useState(() => 16 | createBrowserSupabaseClient() 17 | ); 18 | useEffect(() => { 19 | document.body.classList?.remove('loading'); 20 | }, []); 21 | 22 | return ( 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
32 | ); 33 | } 34 | -------------------------------------------------------------------------------- /styles/main.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | *, 6 | *:before, 7 | *:after { 8 | box-sizing: inherit; 9 | } 10 | 11 | *:focus { 12 | @apply outline-none ring-2 ring-pink-500 ring-opacity-50; 13 | } 14 | 15 | html { 16 | height: 100%; 17 | box-sizing: border-box; 18 | touch-action: manipulation; 19 | font-feature-settings: 'case' 1, 'rlig' 1, 'calt' 0; 20 | } 21 | 22 | html, 23 | body { 24 | font-family: -apple-system, system-ui, BlinkMacSystemFont, 'Helvetica Neue', 25 | 'Helvetica', sans-serif; 26 | text-rendering: optimizeLegibility; 27 | -moz-osx-font-smoothing: grayscale; 28 | @apply text-white bg-zinc-800 antialiased; 29 | } 30 | 31 | body { 32 | position: relative; 33 | min-height: 100%; 34 | margin: 0; 35 | } 36 | 37 | a { 38 | -webkit-tap-highlight-color: rgba(0, 0, 0, 0); 39 | } 40 | 41 | .animated { 42 | -webkit-animation-duration: 1s; 43 | animation-duration: 1s; 44 | -webkit-animation-duration: 1s; 45 | animation-duration: 1s; 46 | -webkit-animation-fill-mode: both; 47 | animation-fill-mode: both; 48 | } 49 | 50 | .height-screen-helper { 51 | height: calc(100vh - 80px); 52 | } 53 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nextjs-subscription-payments", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "dev": "next", 7 | "build": "next build", 8 | "start": "next start", 9 | "stripe:listen": "stripe listen --forward-to=localhost:3000/api/webhooks --project-name=saas-starter" 10 | }, 11 | "dependencies": { 12 | "@stripe/stripe-js": "^1.48.0", 13 | "@supabase/auth-helpers-nextjs": "^0.5.4", 14 | "@supabase/auth-helpers-react": "^0.3.1", 15 | "@supabase/auth-ui-react": "^0.3.3", 16 | "@supabase/auth-ui-shared": "^0.1.2", 17 | "@supabase/supabase-js": "^2.10.0", 18 | "classnames": "^2.3.2", 19 | "next": "^13.2.3", 20 | "react": "^18.2.0", 21 | "react-dom": "^18.2.0", 22 | "react-merge-refs": "^2.0.1", 23 | "stripe": "^11.13.0", 24 | "swr": "^2.0.4", 25 | "tailwindcss": "^3.2.7" 26 | }, 27 | "devDependencies": { 28 | "@types/node": "^18.14.4", 29 | "@types/react": "^18.0.28", 30 | "autoprefixer": "^10.4.13", 31 | "postcss": "^8.4.21", 32 | "prettier": "^2.8.4", 33 | "typescript": "^4.9.5" 34 | }, 35 | "prettier": { 36 | "arrowParens": "always", 37 | "singleQuote": true, 38 | "tabWidth": 2, 39 | "trailingComma": "none" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /utils/helpers.ts: -------------------------------------------------------------------------------- 1 | import { Price } from 'types'; 2 | 3 | export const getURL = () => { 4 | let url = 5 | process?.env?.NEXT_PUBLIC_SITE_URL ?? // Set this to your site URL in production env. 6 | process?.env?.NEXT_PUBLIC_VERCEL_URL ?? // Automatically set by Vercel. 7 | 'http://localhost:3000/'; 8 | // Make sure to include `https://` when not localhost. 9 | url = url.includes('http') ? url : `https://${url}`; 10 | // Make sure to including trailing `/`. 11 | url = url.charAt(url.length - 1) === '/' ? url : `${url}/`; 12 | return url; 13 | }; 14 | 15 | export const postData = async ({ 16 | url, 17 | data 18 | }: { 19 | url: string; 20 | data?: { price: Price }; 21 | }) => { 22 | console.log('posting,', url, data); 23 | 24 | const res: Response = await fetch(url, { 25 | method: 'POST', 26 | headers: new Headers({ 'Content-Type': 'application/json' }), 27 | credentials: 'same-origin', 28 | body: JSON.stringify(data) 29 | }); 30 | 31 | if (!res.ok) { 32 | console.log('Error in postData', { url, data, res }); 33 | 34 | throw Error(res.statusText); 35 | } 36 | 37 | return res.json(); 38 | }; 39 | 40 | export const toDateTime = (secs: number) => { 41 | var t = new Date('1970-01-01T00:30:00Z'); // Unix epoch start. 42 | t.setSeconds(secs); 43 | return t; 44 | }; 45 | -------------------------------------------------------------------------------- /pages/api/create-portal-link.ts: -------------------------------------------------------------------------------- 1 | import { NextApiHandler } from 'next'; 2 | import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'; 3 | 4 | import { stripe } from '@/utils/stripe'; 5 | import { createOrRetrieveCustomer } from '@/utils/supabase-admin'; 6 | import { getURL } from '@/utils/helpers'; 7 | 8 | const CreatePortalLink: NextApiHandler = async (req, res) => { 9 | if (req.method === 'POST') { 10 | try { 11 | const supabase = createServerSupabaseClient({ req, res }); 12 | const { 13 | data: { user } 14 | } = await supabase.auth.getUser(); 15 | 16 | if (!user) throw Error('Could not get user'); 17 | const customer = await createOrRetrieveCustomer({ 18 | uuid: user.id || '', 19 | email: user.email || '' 20 | }); 21 | 22 | if (!customer) throw Error('Could not get customer'); 23 | const { url } = await stripe.billingPortal.sessions.create({ 24 | customer, 25 | return_url: `${getURL()}/account` 26 | }); 27 | 28 | return res.status(200).json({ url }); 29 | } catch (err: any) { 30 | console.log(err); 31 | res 32 | .status(500) 33 | .json({ error: { statusCode: 500, message: err.message } }); 34 | } 35 | } else { 36 | res.setHeader('Allow', 'POST'); 37 | res.status(405).end('Method Not Allowed'); 38 | } 39 | }; 40 | 41 | export default CreatePortalLink; 42 | -------------------------------------------------------------------------------- /components/icons/GitHub.tsx: -------------------------------------------------------------------------------- 1 | const GitHub = ({ ...props }) => { 2 | return ( 3 | 10 | 16 | 17 | ); 18 | }; 19 | 20 | export default GitHub; 21 | -------------------------------------------------------------------------------- /components/ui/Button/Button.tsx: -------------------------------------------------------------------------------- 1 | import cn from 'classnames'; 2 | import React, { forwardRef, useRef, ButtonHTMLAttributes } from 'react'; 3 | import { mergeRefs } from 'react-merge-refs'; 4 | 5 | import LoadingDots from '@/components/ui/LoadingDots'; 6 | 7 | import styles from './Button.module.css'; 8 | 9 | interface Props extends ButtonHTMLAttributes { 10 | variant?: 'slim' | 'flat'; 11 | active?: boolean; 12 | width?: number; 13 | loading?: boolean; 14 | Component?: React.ComponentType; 15 | } 16 | 17 | const Button = forwardRef((props, buttonRef) => { 18 | const { 19 | className, 20 | variant = 'flat', 21 | children, 22 | active, 23 | width, 24 | loading = false, 25 | disabled = false, 26 | style = {}, 27 | Component = 'button', 28 | ...rest 29 | } = props; 30 | const ref = useRef(null); 31 | const rootClassName = cn( 32 | styles.root, 33 | { 34 | [styles.slim]: variant === 'slim', 35 | [styles.loading]: loading, 36 | [styles.disabled]: disabled 37 | }, 38 | className 39 | ); 40 | return ( 41 | 53 | {children} 54 | {loading && ( 55 | 56 | 57 | 58 | )} 59 | 60 | ); 61 | }); 62 | 63 | export default Button; 64 | -------------------------------------------------------------------------------- /pages/api/create-checkout-session.ts: -------------------------------------------------------------------------------- 1 | import { NextApiHandler } from 'next'; 2 | import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'; 3 | 4 | import { stripe } from '@/utils/stripe'; 5 | import { createOrRetrieveCustomer } from '@/utils/supabase-admin'; 6 | import { getURL } from '@/utils/helpers'; 7 | 8 | const CreateCheckoutSession: NextApiHandler = async (req, res) => { 9 | if (req.method === 'POST') { 10 | const { price, quantity = 1, metadata = {} } = req.body; 11 | 12 | try { 13 | const supabase = createServerSupabaseClient({ req, res }); 14 | const { 15 | data: { user } 16 | } = await supabase.auth.getUser(); 17 | 18 | const customer = await createOrRetrieveCustomer({ 19 | uuid: user?.id || '', 20 | email: user?.email || '' 21 | }); 22 | 23 | const session = await stripe.checkout.sessions.create({ 24 | payment_method_types: ['card'], 25 | billing_address_collection: 'required', 26 | customer, 27 | line_items: [ 28 | { 29 | price: price.id, 30 | quantity 31 | } 32 | ], 33 | mode: 'subscription', 34 | allow_promotion_codes: true, 35 | subscription_data: { 36 | trial_from_plan: true, 37 | metadata 38 | }, 39 | success_url: `${getURL()}/account`, 40 | cancel_url: `${getURL()}/` 41 | }); 42 | 43 | return res.status(200).json({ sessionId: session.id }); 44 | } catch (err: any) { 45 | console.log(err); 46 | res 47 | .status(500) 48 | .json({ error: { statusCode: 500, message: err.message } }); 49 | } 50 | } else { 51 | res.setHeader('Allow', 'POST'); 52 | res.status(405).end('Method Not Allowed'); 53 | } 54 | }; 55 | 56 | export default CreateCheckoutSession; 57 | -------------------------------------------------------------------------------- /pages/signin.tsx: -------------------------------------------------------------------------------- 1 | import { useRouter } from 'next/router'; 2 | import { useEffect } from 'react'; 3 | import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'; 4 | import { Auth } from '@supabase/auth-ui-react'; 5 | import { ThemeSupa } from '@supabase/auth-ui-shared'; 6 | 7 | import LoadingDots from '@/components/ui/LoadingDots'; 8 | import Logo from '@/components/icons/Logo'; 9 | import { getURL } from '@/utils/helpers'; 10 | 11 | const SignIn = () => { 12 | const router = useRouter(); 13 | const user = useUser(); 14 | const supabaseClient = useSupabaseClient(); 15 | 16 | useEffect(() => { 17 | if (user) { 18 | router.replace('/account'); 19 | } 20 | }, [user]); 21 | 22 | if (!user) 23 | return ( 24 |
25 |
26 |
27 | 28 |
29 |
30 | 48 |
49 |
50 |
51 | ); 52 | 53 | return ( 54 |
55 | 56 |
57 | ); 58 | }; 59 | 60 | export default SignIn; 61 | -------------------------------------------------------------------------------- /components/Layout.tsx: -------------------------------------------------------------------------------- 1 | import { PropsWithChildren } from 'react'; 2 | import Head from 'next/head'; 3 | import { useRouter } from 'next/router'; 4 | 5 | import Navbar from '@/components/ui/Navbar'; 6 | import Footer from '@/components/ui/Footer'; 7 | 8 | import { PageMeta } from '../types'; 9 | 10 | interface Props extends PropsWithChildren { 11 | meta?: PageMeta; 12 | } 13 | 14 | export default function Layout({ children, meta: pageMeta }: Props) { 15 | const router = useRouter(); 16 | const meta = { 17 | title: 'Next.js Subscription Starter', 18 | description: 'Brought to you by Vercel, Stripe, and Supabase.', 19 | cardImage: '/og.png', 20 | ...pageMeta 21 | }; 22 | 23 | return ( 24 | <> 25 | 26 | {meta.title} 27 | 28 | 29 | 30 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
{children}
47 |