Firebase Basic Authentication Part 1
lessonDuration 6m 9sFree
Firebase has several ways to provide authentication for your AngularJS application. In this lesson, Lukas will look at the most basic email/password approach.
Browse
Find courses, lessons, articles, talks, and podcasts.
50 results for "firebase"
Showing 25–48 · Page 2 of 3
lessonDuration 6m 9sFree
Firebase has several ways to provide authentication for your AngularJS application. In this lesson, Lukas will look at the most basic email/password approach.
lessonDuration 4m 25sFree
When using Firebase collections in your AngularJS application, you have access to a handy set of events emitted by the collection when changes in your data occur. Be sure to check out the [first lesson](https://egghead.io/lessons/angularjs-get-started-with-firebase-and-angularfire) in this series for the project source code.
lessonDuration 2m 53sFree
The Firebase Forge provides a convenient GUI for visualizing and manipulating your data in real-time. Be sure to check out [this lesson](https://egghead.io/lessons/angularjs-get-started-with-firebase-and-angularfire) for getting Firebase setup.
lessonDuration 6m 10sFree
Firebase provides a real-time syncing backend for your AngularJS applications in very few lines of code. In this lesson, you'll learn how to get started integrating it into your app.
lessonDuration 3m 33s
We'll go through a quick intro to the 2 different types of data in Firestore: documents and collections. A document is an object and a collection is a list of documents. Then we'll learn how to fetch a collection of documents from Firestore and display it in our application. We'll do this through API that Firestore offers us. In this case we'll call `collectionData` and pass in the `collection` function with a key of tasks that matches our collection in the Firestore.
lessonDuration 5m 32s
We'll go through the process of adding a new property to our task and how to update our task document in the database. Because we are using a `BehaviorSubject` we can utilize the `.next` function on the `task$` to add the assignee. We'll also explore the use of action sheets to use as selectors.
lessonDuration 2m 1s
A scenario you will inevitably run into is users needing to reset their passwords for security reasons or they lost and forgot their password. We'll learn how to send our users an email to reset their passwords, after we send the email, we'll display a notification alert with ionic alertController to the user and redirect them to the login page.
lessonDuration 2m 29s
Our Security Rules are getting repetitive with all the logic that we've copy and pasted for the several actions we currently have. In this lesson, we'll go through our security rules and extract the duplicated rules into functions that we can call. With this approach, we can eliminate the copy/pasting and make our functions a bit more readable.
lessonDuration 3m 41s
We want our users to have more power by uploading and downloading files to the tasks they create. In this lesson, we'll start creating the functionality that will allow our users to upload files. I went ahead and created the UI and click handler for this feature so we can focus on the actual file uploading. We'll use the browser's `<input type="file">` to select files from our device and then we'll use Cloud Storage methods to upload the file to our storage bucket.
lessonDuration 3m 54s
Now that file uploading works, we want to actually show that a task has files associated with it. To do this we will need to update the task object with a file property that we'll push files too. In this lesson, we'll use Cloud Storage methods like getDownloadUrl() to get the file's download URL from our bucket. Then we'll add that file's information to our task and persist it in the database to show the list of files in a task to the user. While we do this, you'll see how we can easily add a spinner when files are being uploaded using Ionic loadingController.
lessonDuration 1m 4s
Users can now see that files are attached to tasks but they can't do much with that. We need to let users be able to download the files so we'll do that in this lesson. We'll create a button for users to download the files they have in their tasks. We take a JavaScript first approach here by creating an anchor tag and adding all of the properties we need to allow for a download.
lessonDuration 3m 32s
We want to secure our file storage so not just anyone can upload files to our Cloud Firestore. We'll go through Cloud Storage Security rules to add rules and restrictions to our bucket server-side. You'll notice that the default rules for storage are the same as the database in that they are open to anyone for 30 days. There are a few restrictions that we will implement: - Only allowing authenticated users to upload files. - Restrict the size of the files we want to upload. - Restrict the type of files we want to upload. (__i.e: only accept images or pdfs__)
lessonDuration 2m 54sFree
There are 2 different ways to get a document's ID when using `@angular/fire`. You can add the parameter `{ idField: 'id' }` to your collection when using the `collectionData()` observable. You can also use the observable `collectionChanges()` and access the internal metadata of the document to manually get the ID and add it to the resulting object. Code sample: https://github.com/javebratt/angularfire-idField
lessonDuration 4m 6s
Emulator data is lost on restart since it is all in memory. In this lesson we'll take advantage of Firebase's emulator export script and `--import` flag so that we will always have seeded data when we start our app.
article
Hey Everyone 👋, John Lindquist here with the **tenth issue of AI Dev Essentials!** This week has been absolutely monumental for the AI coding space. Cursor hitting 1.0 and raising $900 million at a nearly $10 billion valuation is a watershed moment for AI-assisted development. The speed at which they've grown—from $1 million to over $500 million in ARR in just over two years—shows just how hungry developers are for better AI coding tools. And with background agents now generally available, we're entering a new era where AI can truly work alongside us asynchronously. I've personally spent a lot of time withe the "Claude Code" experience the past week to compare it to Cursor. I totally understand the appeal, especially because of how reliably Claude Code can churn away at long tasks (and you're not thinking about burning through requests/costs), but Cursor is still a superior experience when it comes to gathering context and reviewing changes. I'm hoping this puts pressure on the Cursor team to release a "MAX" plan similar to Claude's "MAX" plan. I like having a budget, but I don't like thinking every failed tool call is lost money. I try to remember that we're still all in the super early days of AI, and everyone is just figuring it out as they go. With that said, let's dive into this week's updates! ### 🎓 New egghead.io Lessons This Week I'm working on a course "Building Local AI Agents with Ollama and the AI SDK". I'm 5 lessons in and I'm excited to share them, but just not quite ready. They should be up when this newsletter rolls around next week, so keep an eye out for that. 😇 --- ## 🚀 Cursor 1.0 & The $900M Funding Round **Cursor has officially hit 1.0 and raised $900 million at a $9.9 billion valuation** This week brought two massive announcements from Cursor that cement its position as the leader in AI coding assistants. First, the 1.0 release brings game-changing features like BugBot for automated code review, background agents for asynchronous work, and seamless GitHub integration. Then came the funding news: $900 million led by Thrive Capital, with participation from Andreessen Horowitz, Accel, and DST Global. **Key Stats:** - Over $500 million in ARR (growing 60% since April) - Used by more than half of the Fortune 500, including NVIDIA, Uber, and Adobe - ARR has been doubling approximately every two months **Cursor 1.0 Features:** - **BugBot**: Automatically reviews PRs and catches potential bugs with "Fix in Cursor" integration - **Background Agent**: Now GA, lets you spawn AI workers for parallel tasks in remote environments - **Memories**: Per-project context retention so AI doesn't forget key facts - **Jupyter Support**: AI can now work inside .ipynb notebooks - **One-click MCP setup**: Streamlined installation for MCP servers ([TechCrunch Coverage](https://techcrunch.com/2025/06/05/cursors-anysphere-nabs-9-9b-valuation-soars-past-500m-arr/), [DEVCLASS Analysis](https://devclass.com/2025/06/06/cursor-ai-editor-hits-1-0-milestone-including-bugbot-and-high-risk-background-agents/)) > I do love seeing money being poured into companies that are building AI tools for developers. I'm hoping that the leads to customized models that are smarter, faster, with reliable tool calling, and features around "agent swarms" that can tackle complex tasks in parallel. I'm really excited to see what sorts of UIs emerge for orchestrating these agents. --- ## 🧠 Model & Platform Updates ### OpenAI o3 & o3-pro: Major Price Drop and Release OpenAI made significant waves this week with two major announcements. First, Sam Altman confirmed an 80% price reduction for o3, making it viable as a "daily driver" model. Cursor immediately updated their pricing to reflect this change, noting that "o3 is a fantastic model, and we're excited that it can now be used as a daily driver." Then came **o3-pro**, OpenAI's most advanced reasoning model yet. Community consensus is forming around its capabilities and limitations: **o3-pro Strengths:** - Excels at math competitions and scientific reasoning - Handles complex multi-step problems with deeper thinking - Acts as a "superhuman researcher + structured thinker" capable of processing massive amounts of data - Demonstrates impressive performance on challenging tests like the "reindeer" problem **Community Reality Check:** - Not ideal as a daily coding model—better suited for complex reasoning tasks - Mixed results on real-world coding: One developer reported it failed to fix type errors, reducing 34 errors to only 28 despite confident promises - Most users don't need this level of reasoning power for everyday tasks - Best used for research, analysis, and uncovering insights you might miss **Codex Gets Internet Access**: OpenAI also rolled out internet access for Codex, allowing it to install dependencies, run tests with external resources, and upgrade packages during task execution. The feature is off by default and provides granular control over allowed domains and HTTP methods. > This all rolled out last night. I haven't had a chance to dig in to o3-pro, so I just gathered a bunch of early impressions from the community above. I'll have my own personal take next week. ### Gemini 2.5 Pro Tops WebDevArena Google's updated Gemini 2.5 Pro continues to excel at coding, now leading WebDevArena with a 1443 Elo score (35-point jump). The update introduces: - **Thinking budgets** for cost/latency control - Enhanced coding performance for complex web apps - Improved style and structure in responses - GA coming in the next few weeks - **New SOTA on Aider Polyglot**: The upcoming GA version scores 86.2%, beating the previous version by 10 percentage points ([Google Blog](https://blog.google/products/gemini/gemini-2-5-pro-latest-preview/), [9to5Google](https://9to5google.com/2025/06/05/gemini-2-5-pro-preview-06-05/)) > Gemini 2.5 Pro is in this interesting place where it's _awesome_, but still a bit difficult to work with in Cursor. I really, really want to use it as my daily driver, but the thinking process often seems to spin too much. I'm hoping a Cursor system prompt (or a community propmt) will emerge to help smooth it all out. The results have always been great, but sometimes it ends up taking too long and my patience wears out. ### Mistral Launches Magistral: Multilingual Reasoning Models Mistral AI announced Magistral, their first reasoning models designed to excel in domain-specific, transparent, and multilingual reasoning. The models come in two variants: - **Magistral Small (24B)**: Open-source under Apache 2.0 license - **Magistral Medium**: Enterprise version with enhanced capabilities Key differentiators include multilingual reasoning (especially strong in European languages), 10x speed improvements in Le Chat, and transparent thinking processes users can follow and verify. ([CNBC Report](https://www.cnbc.com/2025/06/10/microsoft-backed-ai-lab-mistral-debuts-reasoning-model-to-rival-openai.html), [TechCrunch](https://techcrunch.com/2025/06/10/mistral-releases-a-pair-of-ai-reasoning-models/)) > Any open-source news is good news. While I'm happy to pay providers for "premium" access to models, I'm still hopeful open-source will unlock AI for everyone down the road. I just never make time to test the open-source models with so much else happening at the same time. --- ## 💰 Major Funding & Business Updates ### Linear Raises $82M at $1.25B Valuation for AI Agent Platform Linear secured $82 million in Series C funding led by Accel, positioning itself as "the place where teams, AI, and agents build software together." With 280% profit growth and over 15,000 customers including OpenAI, Scale AI, and Perplexity, Linear is focusing on making their platform the natural home for AI agents to coordinate work across product workflows. ([Reuters](https://www.reuters.com/business/atlassian-competitor-linear-raises-funding-125-billion-valuation-2025-06-10/), [Linear Blog](https://linear.app/blog/building-our-way)) > I included this because Linear's MCP is a popular MCP for agents. So far, everyone uses so many variations of "AI Task Tracking" and it seems like Linear is raising to the top. Seeing them focus on AI-specific language and raising money is only a good sign (maybe Cursor will buy them or spin off their own version someday?) --- ## 🛠️ Developer Tools & Ecosystem ### Vertex AI Studio Gets Major Redesign Google Cloud unveiled a redesigned Vertex AI Studio with a developer-first approach: - Dark mode support across the platform - Unified UI combining Chat and Freeform prompting - Easy grounding with Google Search or Maps - Direct code generation for Python, Android, Swift, Web, Flutter - Access to 200+ foundation models including Gemini, Llama, and Claude ([Google Cloud Blog](https://cloud.google.com/blog/products/ai-machine-learning/vertex-ai-studio-redesigned)) ### ElevenLabs Launches v3 with Emotion Control ElevenLabs v3 introduces revolutionary emotion direction through audio tags: - Control emotions with tags like [excited], [whispers], [sighs], [laughs] - 70+ language support - Enhanced expressiveness and contextual understanding - Multi-speaker dialogue with matching prosody ([ElevenLabs v3](https://elevenlabs.io/v3), [Documentation](https://elevenlabs.io/blog/eleven-v3)) > These voices are _so good_. I'm tempted to toss one of my favorite books in their ("The Silent Gondoliers") and go on a road trip to see how they handle full narration. ### OpenAI Agents SDK Now in TypeScript OpenAI released their Agents SDK in TypeScript with full feature parity to Python: - Human-in-the-loop approvals - Handoffs, guardrails, tracing, MCP support - RealtimeAgent for voice interactions - Enhanced Traces dashboard for Realtime API sessions ([OpenAI Developers](https://openai.github.io/openai-agents-js/)) > TypeScript is arguably _the_ language for building AI agents thanks to all the hosting/endpoints/etc already built for it. For most platforms, it becomes trivial to plop in a TypeScript SDK package, an API key, and spin up Agents. --- ## 🔧 Quick Updates - **Prisma Local Development**: `npx prisma dev` now persists data between sessions and supports multiple instances without Docker ([Prisma Blog](https://www.prisma.io/blog/prisma-6-8-0-release)) - **OpenAI Advanced Voice**: Updated for more natural conversations with improved translation capabilities - **Firebase Studio**: Turn Figma designs into working apps with Gemini integration ([Firebase Blog](https://firebase.blog/posts/2025/05/whats-new-at-google-io/)) - **Supermemory MCP**: Now open source for infinite chat context ([GitHub](https://github.com/supermemoryai/supermemory-mcp)) - **Taskmaster v0.16**: New .taskmaster folder structure with Bedrock, Azure, and Vertex AI support ([GitHub](https://github.com/eyaltoledano/claude-task-master)) - **Ask-Human MCP**: New zero-config tool for human-in-the-loop verification—pauses agents when unsure, logs questions to `ask_human.md`, resumes when you provide answers ([GitHub](https://github.com/Masony817/ask-human-mcp)) - **AI Studio Clarification**: Google's Logan Kilpatrick confirmed AI Studio free tier isn't going away—it's transitioning to API key-based access with continued free tier availability --- ## 🤖 AI Research & Observations ### AIs Play Diplomacy: Revealing Model Personalities A fascinating experiment had different AI models play the strategy game Diplomacy, revealing distinct behavioral patterns: - **Claude** couldn't lie and was exploited ruthlessly by other players - **Gemini 2.5 Pro** nearly conquered Europe with brilliant tactical gameplay - **o3** orchestrated secret coalitions, backstabbed every ally, and won This real-world test highlights how different models exhibit varying levels of strategic thinking, deception capability, and goal-oriented behavior—important considerations when choosing models for different applications. > I'm hoping someday these can turn into live visual competitive storytelling experiences. Kind of like a battlebots tournament, but with AI models. I'll admit I'm also hiding my head in the sand when it comes to using AI to "dominate" anything. (I love you AI Overlords! ❤️) ### Anthropic Cuts Windsurf API Access In a surprising move, Anthropic reportedly restricted Windsurf's API access to Claude models. This development raises questions about the competitive dynamics between AI providers and coding assistant platforms. ([TechCrunch](https://techcrunch.com/2025/06/10/anthropic-windsurf-api-access-restricted/)) > Seems fair IMO. OpenAI bought Windsurf. OpenAI competes with Anthropic. Why would Anthropic want to help OpenAI make money? --- ## 💡 Security & Best Practices **Vercel on AI Agent Security**: New guidance on prompt injection vulnerabilities emphasizes: assume compromise, limit tool call access, and don't trust output. Essential reading for anyone building AI agents. ([Vercel Blog](https://vercel.com/blog/building-secure-ai-agents)) --- ## ✨ Workshop Spotlight: Conquer the Complexity of Cursor ✨ Master practical AI development workflows in Cursor. This hands-on workshop covers Agents, Ask mode, Custom Modes, multi-file analysis, effective prompting, Cursor rules, and strategies for handling AI failures. - **When:** _Friday, June 27, 2025, 9:00 AM - 2:00 PM (PDT)_ - **Where:** Zoom (Live Q&A included) - **Investment:** $249 (early bird prcing of $200 until June 18th) ➡️ [**Read More about the Workshop**](https://egghead.io/workshop/cursor) ➡️ [**Register Now ($249)**](https://buy.stripe.com/7sY7sEbOZbGO0kx7pw9fW09?prefilled_promo_code=GEUHPI9B) _(Team training also available)_ --- That's all for this milestone tenth issue! The convergence of massive funding, breakthrough features, and growing enterprise adoption shows we're at an inflection point for AI-assisted development. The tools are getting more powerful, the agents more capable, and the possibilities more exciting. If you have any feedback or questions, hit reply. I'm happy to chat about the latest in AI dev tools. John Lindquist [egghead.io](https://egghead.io)
article
Hey Everyone 👋, John Lindquist here with the second issue of AI Dev Essentials! It's been another busy week in the AI tooling world. The biggest splash was probably GPT-4.1 hitting the streets, but there's plenty more action around MCP, Vercel's v0, Google's developer tools, and interesting community discussions. I've spent some time with GPT-4.1 already (specifically in Cursor), and while it shows promise, it didn't quite convince me to switch from Gemini 2.5 Pro yet. It stumbled on a few basic requests where Gemini usually shines on the first attempt. --- ### New egghead.io Lesson This Week: * **[Create a Custom MCP that Calls Cursor Tools](https://egghead.io/create-a-custom-mcp-that-calls-cursor-tools~r77sw):** Learn how to build custom MCP server tools that allow Cursor's AI Agent to access your local project context. This lesson shows how to use Zod schemas and the crucial `.describe()` method to explicitly request information (like Git status or version) from the Cursor environment *before* your tool runs, enabling powerful, context-aware automation. --- Here are the highlights that caught my eye this past week. ## Model Mania: GPT-4.1 Arrives, Plus Grok & Llama Updates * **GPT-4.1 Lands:** OpenAI announced GPT-4.1, and it quickly became available via the [API](https://openai.com/live/) and showed up in [Cursor](https://x.com/cursor_ai/status/1911835651810738406). Cursor is offering it free for now to let users get a feel for it, though they don't recommend it as a default just yet. Curious to hear initial impressions from folks testing it out for coding tasks. * **Grok 3 in Cursor:** Following other model additions, [Cursor also enabled Grok 3 models](https://x.com/amanrsanger/status/1910434915419906141), with the mini version available for free users. Aman Sanger noted it seems to "think upfront more than other models." * **Community Hack: Llama 4.0 via Groq in Cursor:** Levi Dan shared a [detailed (and slightly hacky) guide](https://x.com/lxvi_brg/status/1908865544721154455) on how to wire up Groq's fast Llama 4.0 API into Cursor by using the OpenAI API key slot and intercepting requests. A clever workaround for the adventurous! ## Tooling & Platform Pulse Lots of movement across different platforms and tools this week: * **Vercel Ecosystem:** * Guillermo Rauch teased [v0 coming to VS Code](https://x.com/rauchg/status/1911524154458984515), hinting at tighter integration for the UI generation tool. * v0 also [added AI integrations](https://x.com/v0/status/1911912183149256943) with models from xai (Grok), FAL, Groq, and DeepInfra, including automatic API key setup and pay-as-you-go billing via Vercel Marketplace. They're offering a $10 credit for the Grok free tier. * Vercel shared insights on the [grep.app migration from CRA to Next.js](http://grep.app/), showcasing performance improvements. ([Source](https://x.com/rauchg/status/1911920410020757881)) I'm personally excited about this one – I rely heavily on examples when working with AI, and for me, a good example is often worth ten prompts. Tools like `grep.app` that make code discovery easier are invaluable. * **Google's Growing Stack:** * Project IDX has officially become [Firebase Studio](https://x.com/_davideast/status/1909990728593453455), positioning itself as a cloud-based, agentic dev environment for full-stack AI apps, deeply integrated with Firebase. I've tried spinning up a few sites with it, and the speed is impressive. However, for more complex tasks like designing from images or intricate interactions, I still find myself leaning towards v0 for now. * Google quietly released the [Agent Development Kit (ADK)](https://x.com/omarsar0/status/1910004370864742757), a Python library (`pip install google-adk`) for building multi-agent systems with features like state management, tool usage, and orchestration. I haven't had a chance to dive into this yet, but it's right at the top of my list. Building robust agent systems is a huge area of interest, so this is probably the announcement I'm most excited about exploring this week. * Ramón Medrano Llamas shared his experience [moving back to VS Code from Cursor](https://x.com/rmedranollamas/status/1909516749612999149), highlighting the effectiveness of GitHub Copilot combined with the Gemini Code Assist extension (using Gemini 2.5 Pro in Agent Mode). I gave the Gemini Code Assist extension a try myself, but as someone deeply embedded in the Cursor workflow with established keyboard shortcuts and patterns, I struggled to find a flow I liked and didn't stick with it for long. It's interesting to see different perspectives, though! * AI features are rolling out more broadly in [Chrome](https://x.com/iam_chonchol/status/1909942954686636224), including text grabbing from YouTube videos and Google Lens integration. * **Cloudflare Corner:** * Big news for edge compute: [Cloudflare Containers are coming to Open Beta in June](https://x.com/CherryJimbo/status/1910682562499850405), enabling running containerized apps (Next.js, Go, PHP confirmed) directly on the edge. This is huge news, in my opinion. Think about all the WordPress sites and other applications that rely on containerization. Opening this up on the edge unlocks incredible possibilities, including for AI applications. I'm super hyped to see what people build with this come June. * A new tool, [MCPify.ai](http://mcpify.ai/), launched for building MCP servers conversationally, built entirely on Cloudflare Workers and Durable Objects. ([Source](https://x.com/pbteja1998/status/1911723180445610149)) * Securing MCP servers is getting easier, with examples shared using [WorkOS AuthKit](https://x.com/WorkOS/status/1910722639036874943) and [Auth0](https://x.com/dschenkelman/status/1910693265566728319). * **IDE Updates:** * JetBrains shared the public [WebStorm roadmap for March-April](https://youtrack.jetbrains.com/issue/WEB-72310). ([Source](https://x.com/WebStormIDE/status/1909291367504748937)) > **✨ Workshop Spotlight: Conquer the Complexity of Cursor (Europe Friendly Time!) ✨** > > Missed the last workshop or found the timing tricky? This one's for you! Master practical AI development workflows in Cursor in a session scheduled for **12:00 PM UTC** to better accommodate European attendees. > > This hands-on workshop covers Agents, Ask, Custom Modes, multi-file analysis, effective prompting, Cursor rules, and strategies for handling AI failures. Unlock Cursor's potential and streamline your development process. > > * **When:** \[Check website for upcoming dates - This session is Europe-friendly at 12:00 PM UTC\] > > * **Where:** Zoom (Live Q&A included) > > * **Investment:** $149 > > ➡️ [**Read More about the Workshop**](https://egghead.io/workshop/cursor) > ➡️ [**Register Now ($149)**](https://buy.stripe.com/7sI7tT81dfpC06s28c) > > *(Team training also available)* ## Community Buzz & Resources * **MCP Explained:** Kent C. Dodds wrote a piece explaining [why he's excited about Model Context Protocol (MCP)](https://www.epicai.pro/the-game-changing-potential-of-model-context-protocol) and its potential. ([Source](https://x.com/kentcdodds/status/1911840456432034112)) * **Prompting Guide:** Ian Nuttall surfaced [v7 of Google's Prompt Engineering Guide](https://x.com/iannuttall/status/1911086164196606314), a deep dive into techniques and best practices. Definitely worth a look. * **Discussion Starter:** Eric Zakariasson asked the community about their [favorite CLIs and MCP servers to use with the Cursor agent](https://x.com/ericzakariasson/status/1910808935961088346). What are you all using? * **Gemini 2.5 Pro Praise:** The positive buzz around Gemini 2.5 Pro continues to grow in the community. It's getting rave reviews and even achieving 'S-tier' status on social platforms like Reddit for its coding capabilities. ([Source](https://x.com/suchenzang/status/1911251230317490416)) That’s a wrap for this week! There's always so much happening, it's hard to keep up, but hopefully, this helps surface some of the more interesting bits for developers working with AI. If you have any feedback or questions, feel free to respond to this email. Always happy to talk shop about the latest AI tools. John Lindquist [egghead.io](https://egghead.io)
article
# Introduction This article is about my experience building a SaaS application. And while this won't be a step-by-step guide on how to build a SaaS app, I will be providing you valuable insight on what the process was like for me as well as teaching you about the methods and technologies that I used. Software as a Service (SaaS) is a business model whereby the user pays a subscription to access cloud-based services or an application. In my case, I wanted to build an educational course platform where users can purchase an individual course to own for life or pay a subscription to gain access to all premium courses. Before building this application, I had only used Stripe Checkout to process one-off payments. I wanted to use this opportunity to go a little deeper - primarily learning how Stripe handles recurring payments. I plan to implement what I have learned throughout this process into my [site](https://jonmeyers.io/), which will house my premium courses one day. The final version of this SaaS project ended up with a few third-party services, each handling their own piece of the puzzle and using webhooks to keep them in sync. Below is an architecture diagram representing the relationships between those services.  This article will focus on each chunk of the stack individually. I will talk through why I chose each technology and discuss any problems I ran into during the process. [Here is the project repo](https://github.com/dijonmusters/courses) for those after the code and a [live version of the final project named "Courses"](https://courses-saas.vercel.app/). FYI, payments are real! You have been warned, and thank you for your donation! 😆 # What will be covered? - High-level explanation of why certain technologies were chosen - Biggest problems encountered throughout and how they were solved - Next.js and the use cases for pregeneration vs serverside rendering - Hosting, secrets, and automatic deploys with Vercel - Prisma as an ORM, as well as the project's database schema and migrations - Using Auth0 for authentication, GitHub as a social provider, and webhooks to keep things in sync - Stripe for individual payments, subscriptions, and more webhooks! # What will not be covered? - A step-by-step guide for building a SaaS project - I wrote a [blog article each week](https://jonmeyers.io/blog/build-a-saas-platform-with-stripe) as I was building the project, which goes into more granular detail. [](https://egghead.io/courses/build-a-saas-product-with-next-js-supabase-and-stripe-61f2bc20?utm_source=blog_post&utm_medium=course_cta&utm_term=supabase) # Tech stack - **Next.js** was used to build the UI, as well as the small chunks of server-side logic required for fetching gated content from Prisma, initiating authentication with Auth0, and payments with Stripe - **Vercel** was used as a hosting platform for the application and its serverless functions - **Prisma** provides a beautiful query-building language to abstract away those scary, complex SQL queries - **Supabase** was used to host a Postgres database instance - it is capable of so much more around authentication and real-time database events, but we already had those pieces solved - **Auth0** was used to authenticate users with GitHub, manage sessions and protect both client and API routes in Next.js - **Stripe** was used to process payments, subscriptions and host a customer portal for users to manage their subscription and payment information # The app When considering different framework options to build the app, I had already decided that React would be the foundation - I have the most experience with it, and it makes me the most productive. I wanted to be able to pre-generate (build static pages) any un-gated/public content. This gave me a few options: **Handcrafted React and Node server** ❌ Too much work! **Gatsby** ✅ Awesome framework ✅ Static generation of pages at build time **Next.js** ✅ Also an awesome framework ✅ Static generation of pages at build time ✅ Server-side rendered pages ✅ API routes (serverless functions) I chose Next.js primarily because of its server-side rendering. Authentication would be a big part of this project, so I wanted to have an easily accessible server to handle all that secret stuff! While Gatsby spins up a server when building an application, that server does not exist when your users are using the app. Therefore, if I wanted to do secret stuff, I would have to manage another server! That sounds like too much work! Additionally, with so many different technologies being used already, and one of the main outcomes of this project being a case study to share with people, I didn't want to throw in the mental overhead of GraphQL, which is somewhat unescapable with Gatsby - GraphQL is awesome. Still, we can cover it at another time! ## Pregeneration (SSG) Pregeneration is the process of fetching all the data for a page when building the application. This means we can request data from slow servers, do expensive computational tasks, etc., without every user needing to sit and watch a loading spinner. We do all these slow tasks once, build static HTML pages with the data, and then serve them as static assets - much cheaper to host and scale! Next.js makes pregeneration super easy! All you need to do is export a function called `getStaticProps` from a page-level component. It will pick this up when building the application, run the function and inject the result into the component. Here is a simple example of how this can be used. ```jsx const BlogsPage = ({ blogs ) => blogs.map(blog => <p>{blog.title}</p>) export const getStaticProps = async () => { const blogs = await getBlogPosts() // fetching from remote API return { props: { blogs, }, } } export default BlogsPage ``` Here is an example from our SaaS application where we need to fetch all of the `prices` from Stripe, then iterate over each one and request its associated `product`. ```jsx const PricingPage = ({ plans }) => ( // render each plan ) export const getStaticProps = async () => { const { data: prices } = await stripe.prices.list() const plans = await Promise.all( prices.map(async (price) => { const product = await stripe.products.retrieve(price.product) return { id: price.id, name: product.name, price: price.unit_amount, interval: price.recurring.interval, currency: price.currency, } }) ) return { props: { plans, }, } } export default PricingPage ``` In this example, we have two subscription plans, so we would be making three requests - one for the list of `prices` and then an additional request for each one's `product`. Imagine if we had one hundred products. What about a thousand! This could take a while and provide a pretty bad experience for our users 🙁 Remember, happy customers, like to buy our things! If we make these requests when we build our application, then they only happen once - when we deploy. No users are sitting around and waiting for us to deploy. When they visit the site, they get a super snappy pregenerated static page that doesn't need to rely on any third-party services for its data! Pregeneration works amazingly well for public content - pages where you don't care who the user is. Great for marketing pages and things that don't need to change frequently - such as a pricing page. If the page requires a user to be signed in or you are rendering different content for different users - such as a user dashboard - pregeneration is no longer a viable option. The problem is that when the server is building these static pages, there is no user! ## Server-side Rendering (SSR) That's where server-side rendering comes to save the day! This process runs when the user requests the page rather than when the server builds the application. Therefore, we know who the user is and can determine what they should and shouldn't access. Additionally, because this logic is running on the server, we can do secret things - such as fetch premium content from Prisma or check whether the user has a particular role - without worrying whether the user has tinkered with it. NEVER TRUST ANYTHING ON THE CLIENT! We can only trust our server-side code! Again, Next.js makes it super simple to run some server-side code. We export a function called `getServerSideProps`, and it will automagically turn it into a serverless function that runs when the user requests the page. Again, the data returned is injected into the component and displayed to the user. Here is a simplified example of this logic. ```jsx const SecretStuffPage = ({ secretStuff ) => ( <> <NormalStuff /> {secretStuff && <SecretStuff /> </> ) export const getStaticProps = async () => { let secretStuff = null if (user.canSeeSecretStuff) { secretStuff = await getSecretStuff() } return { props: { secretStuff, }, } } export default SecretStuffPage ``` And here is a more realistic example from our application where we only want to display a lesson's video URL if the course is free, paid for, or has an active subscription. ```jsx const LessonPage = ({ videoUrl }) => videoUrl ? ( <video src={videoUrl} /> ) : ( <button onClick={buyCourse}>Buy course</button> ) export const getServerSideProps = async ({ req, res, params }) => { const { slug } = params const session = await getSession(req, res) const email = session?.user?.email let videoUrl = null let user = null const lesson = await getLesson(slug) if (email) { user = await getUser(email) } const userAllowedCourse = lesson.course.price === 0 || user?.isSubscribed || user?.courses.find((course) => course.id === lesson.course.id) if (userAllowedCourse) { videoUrl = lesson.videoUrl } return { props: { videoUrl }, } } export default LessonPage ``` In the above example, `videoUrl` is either null or a URL for the lesson's video, depending on whether the user is allowed to see this content or not. By only returning the bits of data that the user is allowed to see, we make sure that the secret stuff remains secret! If we had returned the entire lesson from `getServerSideProps` and simply checked in the component whether we should display it or not, then that data has still been sent across from the server to the client. The secret stuff is no longer secret! Take this example. ```jsx const LessonPage = ({ lesson, user }) => { console.log(lesson) const userAllowedCourse = lesson.course.price === 0 || user?.isSubscribed || user?.courses.find((course) => course.id === lesson.course.id) return userAllowedCourse ? ( <video src={videoUrl} /> ) : ( <button onClick={buyCourse}>Buy course</button> ) } export const getServerSideProps = async ({ req, res, params }) => { const { slug } = params const session = await getSession(req, res) const email = session?.user?.email let videoUrl = null let user = null const lesson = await getLesson(slug) if (email) { user = await getUser(email) } return { props: { lesson, user }, } } export default LessonPage ``` If we were to run this in the browser, it would seem equivalent to our previous example - the video would only display if the user were allowed to see it. However, if we open the console, the entire lesson object will be displayed - including the `videoUrl`. Once we have sent the page to the browser, it runs on the user's machine and is very easy to tinker with! Therefore, if we only return the bits of the data that the user is allowed to see from `getServerSideProps`, then we can keep the secret stuff secret. Server-side rendering with `getServerSideProps` allows us to encapsulate some logic that we need to run on the server without needing to maintain one. <EmailSubscribeWidget /> # Hosting Next up, we need a place to host this application to share it with the world! Again, there are many options that vary greatly in the amount of control vs. work done for you. Since hosting the application is not the thing my users care about, I wanted to use a service that did as much of the heavy lifting as possible. Netlify and Vercel were the main options I was considering. Netlify is awesome and has recently released a [zero-config plugin that enables all the SSR Next.js magic](https://www.netlify.com/blog/2021/03/16/try-the-new-essential-next.js-plugin-now-with-auto-install/). However, I chose to go with Vercel as they are usually slightly ahead of the curve with new Next.js features - probably because they are the creators and maintainers of that too! Hosting the application was super simple with their CLI. ```jsx vercel --prod ``` That's it! This will deploy a new version of your application with a `.vercel.app` domain. This is now hosted live on the Internet and can be seen by anyone in the world with an Internet connection. Very cool! ## Automatic deploys Automatic deploys with GitHub were also a breeze to configure with Vercel. Just push the code to GitHub, authorize Vercel and tell it which branch.  It will now automatically deploy a new version of our application anytime new commits are pushed to the `master` branch of the `courses` repo. ## Preview deployments Another awesome thing Vercel gives us for free is [Preview Deployments.](https://vercel.com/docs/platform/deployments#preview) It will listen for any changes that we push to branches other than `master` - such as opening a new Pull Request - and automatically deploy a new preview version of our application with its own unique URL. This is an awesome way to test new features or get feedback from the team before something goes live! ## Secrets Next up, we need to tell Vercel all of our secrets! Secrets are the variables our application needs to do all the secret things when running in production. These often include API keys to send authenticated requests to a service, database connection strings, and special values we need for auth stuff. Vercel does environment variables a little differently from other platforms. You first create the secret, then link its value to a particular environment variable. This gives you more control over sharing secrets across multiple projects and granting or restricting particular environments access - e.g., available in production and preview, but not development. Again, super simple to configure. Head over to Settings > Environment Variables and create what you need. There are three different types of Environment Variables in Vercel: 1. Plaintext - things that don't need to be secret - such as API_URL 2. Secret - sensitive values - such as API keys, DB connection strings etc 3. Provided by system - values populated by the system during deployment - such as Preview deploy URL I used `secret` for all of my environment variables. These are made available to your API routes (serverless functions) and any functions that run on the server - `getStaticProps`, `getServerSideProps`, etc. If you would like an environment variable to be available in your client-side code, it must be prepended with `NEXT_PUBLIC_`. In our SaaS application, we have a publishable key from stripe called `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`. You can run the `vercel dev` command locally to run a development server with access to secrets that you have granted the Development permission to, however, I find it easier to just create a `.env` file for secrets running in dev. This is automatically loaded by Next.js and applies the same rules - environment variables available to server-side stuff, variables prepended with `NEXT_PUBLIC_` available client-side. This also means you don't need to add a second copy of your secrets just for dev, or use the same secrets across all of your environments - which is a bad idea! Vercel is an awesome host that makes deployments and hosting super simple. They take care of all the difficult stuff so you can focus on building the thing that makes you money! Additionally, they have a super generous free tier. If you hit the ceiling then you probably have enough users to justify paying Vercel! # Database The next thing we need to consider is what kind of database we need. The first question to ask is whether you actually need a database at all? Could you get away with just using content in markdown files? In my case, I will need to store course content - this sounds great for markdown files - but I also need to know which users have bought particular courses and whether they have subscribed. This might be getting a bit hard to do with markdown. Since we already know we will need to build relationships between different bits of data, a relational database sounds like a good option. Again, there are many options for database hosts with varying levels of management. I decided to go with [Supabase](https://supabase.io/) due to its simplicity of getting up and running. They are an open-source alternative to Google's Firebase and offer so much more than what we are using them for here. Creating a hosted Postgres DB was as simple as authenticating with GitHub and creating a new project. The connection string can be found at Settings > Database > Connection String. Now we need to decide how we want to talk to this database. I'm a huge fan of not manually writing SQL! I can fumble through a query or two but don't trust myself to do it in a performant way. I also have a background in Rails and really like how ORMs (object-relational mappers) abstract away the complexity of writing queries - it feels more like writing code. Prisma is a fantastic ORM that makes building queries that request data across multiple tables super simple and easy to read. Here is an example where we want to find a user based on their email. ```jsx const user = await prisma.user.findUnique({ where: { email: 'jon@gmail.com' } }) ``` If we wanted to also select the courses they had enrolled in (data from another table), we can just tell the Prisma query to include it. ```jsx const user = await prisma.user.findUnique({ where: { email: 'jon@gmail.com' }, include: { courses: true }, }) ``` ## Schema Prisma uses a `schema.prisma` file to define the structure of the database. Models represent different tables and declare the relationships between them. This is the final schema for our SaaS project. ```jsx model User { id Int @id @default(autoincrement()) email String @unique stripeId String @unique isSubscribed Boolean @default(false) courses Course[] createdAt DateTime @default(now()) } model Course { id Int @id @default(autoincrement()) title String @unique description String lessons Lesson[] users User[] price Int slug String @unique createdAt DateTime @default(now()) } model Lesson { id Int @id @default(autoincrement()) title String @unique description String courseId Int course Course @relation(fields: [courseId], references: [id]) videoUrl String slug String @unique createdAt DateTime @default(now()) } ```  A many-to-many relationship - such as a user's courses - can be easily queried like this. ```jsx const user = await prisma.user.findUnique({ where: { email: 'jon@gmail.com' }, include: { courses: true }, }) user.courses // this is an array of courses the user has enrolled in ``` A one-to-many relationship - such as a lesson's course - can be queried like this. ```jsx const lesson = await prisma.lesson.findUnique({ where: { slug: 'intro-to-js' }, include: { course: true }, }) lesson.course // this is the course the lesson belongs to ``` No need for scary joins! ## Migrations Prisma uses migrations to track changes to the database structure - such as adding a new table or column. This is inevitable as a project grows, so having a way to make these incremental changes without breaking things is a must! Prisma validates each change before applying the migration and altering the database structure. This means you get helpful errors and warnings if you try to do something that will modify or destroy existing data. For example, if I tried to remove the ID column on our user model, I get the following helpful error: ```jsx Error validating field `users` in model `Course`: The relation field `users` on Model `Course` references `User` which does not have an `@id` field. Models without `@id` can not be part of a many to many relation. Use an explicit intermediate Model to represent this relationship. ``` To create a migration you just modify the `prisma.schema` file to reflect what you want to change and then run this command to tell Prisma to update the database. ```jsx npx prisma migrate dev ``` ## Seeds Another thing I found particularly useful when making lots of changes to the DB was a `seed.js` file. This can be populated with test data, which makes playing around with database structure much more fun! If you break things too much, just reset the DB and populate with the seed file again! Here is an example course from our SaaS project. ```jsx const { PrismaClient } = require('@prisma/client') const prisma = new PrismaClient() async function main() { await prisma.course.upsert({ where: { title: 'Introduction to JavaScript' }, update: {}, create: { title: 'Introduction to JavaScript', description: "This is a gentle introduction to a super awesome programming language. You're going to love it!", price: 13000, slug: 'introduction-to-javascript', lessons: { create: { title: 'What even is the console?', description: 'The console is where we see super cool stuff!', videoUrl: 'https://www.youtube.com/watch?v=PFljjv6j_YM', slug: 'what-even-is-the-console', }, }, }, }) } main() .catch((e) => { console.error(e) process.exit(1) }) .finally(async () => { await prisma.$disconnect() }) ``` > Using `upsert` makes this file *idempotent*, meaning it can be run over and over again without filling up our database with unnecessary records. # Auth Since we will be locking down premium content to only display for people who have purchased a course or have a subscription, we're going to need to know who they are. For this, we will need them to create an account. Like all of these services, you can manage as much of the process and have as much control as you want. Since I have had fairly limited experience with building authentication solutions, I want something else to stay up to date with all the security best practices and tell me whether a user should have access or not. Auth0 does exactly this - and has done for many, many years. It is yet another awesome service that has a super generous free tier! They also integrate with a huge number of social providers - even things like Strava and Fitbit. This means that users don't need to create yet another account just to use our application. Since my product will be pretty heavily targeted at software developers, I set up the only authentication method to be with GitHub. ## Auth0 and Next.js So, how easy is it to integrate Next.js with Auth0? Install an NPM package and copy in a small amount of starter code! Super easy! Auth0 has built an amazing integration library called `nextjs-auth0`. I recommend checking out their [Getting Started](https://github.com/auth0/nextjs-auth0#getting-started) guide to get everything configured. This library takes care of all the session management logic between the Next.js application and API routes. It also creates new API routes for login, logout, token exchange, and a "me" page to check who is currently logged in. Additionally, it includes a collection of helper functions that we can use in different parts of our application to determine who the user is and whether they should be able to view the content. Check out the [Examples page](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md) to learn more about when to use each one. ## Rules [Auth0 Rules](https://auth0.com/docs/rules) are serverless functions that allow us to run some code during the authentication process - after a user has signed in but before they are redirected to our application. This is the perfect time for us to create a new Prisma user and anything else we need to do to keep our local bits of data in sync with Auth0. This is how we make a request to our SaaS project and tell it to create a new Prisma user. ```jsx async function (user, context, callback) { await request.post('https://courses-saas.vercel.app/api/auth/hooks', { body: JSON.stringify({ email: user.email, }) }); callback(null, user, context); } ``` Since we only want to do this the first time the user logs in, we can set some metadata on our Auth0 user to let us know this has already been done before. ```jsx async function (user, context, callback) { user.app_metadata = user.app_metadata || {}; if (user.app_metadata.localUserCreated) { callback(null, user, context); } else { try { await request.post('https://courses-saas.vercel.app/api/auth/hooks', { body: JSON.stringify({ email: user.email, secret: configuration.AUTH0_HOOK_SECRET, }) }); user.app_metadata.localUserCreated = true; await auth0.users.updateAppMetadata(user.user_id, user.app_metadata); callback(null, user, context); } catch (err) { callback(err); } } } ``` We are also sending across a `secret` value to validate that this request is coming from Auth0. This is our API route to receive the request from Auth0. ```jsx import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() module.exports = async (req, res) => { const { email, secret } = JSON.parse(req.body) if (secret === process.env.AUTH0_HOOK_SECRET) { try { await prisma.user.create({ data: { email }, }) } catch (err) { console.log(err) } finally { await prisma.$disconnect() res.send({ received: true }) } } else { res.send('You forgot to send me your secret!') } } ``` Auth0 will halt the authentication flow until it receives the response from our API. This will eventually timeout and fail to authenticate the user if we forget to send a response. Best not to do anything too computationally expensive here, but perfect for creating a new DB record! This is what the interactions between our application, Auth0 and Prisma look like when a user logs in for the first time.  # Payments Now for the exciting bit! Let's make some money! Stripe is an incredible service for dealing with payments. They take on all the scary credit card stuff so that our application doesn't even need to know about it. We just subscribe to particular Stripe events and update our database accordingly. Again, they have a huge security team constantly updating how they process payments and store data. I do not want that responsibility! Make sure to check out their [pricing page](https://stripe.com/en-au/pricing) to make sure you are happy with what they are charging. Given how easy they make it to set up credit card payments and complex subscriptions without needing to pay upfront, I am pleased with it! ## Creating a Stripe customer Since we will be using Stripe pretty extensively - once-off payments, subscriptions, and a customer portal - we probably want to create a Stripe customer as early as possible and store their ID with our Prisma user. Since we already have a serverless function to keep Auth0 and Prisma in sync, let's also add the Stripe logic. ```jsx import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const stripe = initStripe(process.env.STRIPE_SECRET_KEY) const prisma = new PrismaClient() module.exports = async (req, res) => { const { email, secret } = JSON.parse(req.body) if (secret === process.env.AUTH0_HOOK_SECRET) { try { const customer = await stripe.customers.create({ email, }) await prisma.user.create({ data: { email, stripeId: customer.id, }, }) } catch (err) { console.log(err) } finally { await prisma.$disconnect() res.send({ received: true }) } } else { res.send('You forgot to send me your secret!') } } ``` This is what the interaction looks like between our application, Auth0, Stripe and Prisma when a user signs in for the first time.  ## One-off payments To charge a customer for a course, we need to create a new API route to set up a Stripe session. Remember, we cannot trust any data coming from the client - especially the price! Think about the minimal amount of information you actually need from the user to know what they would like to purchase. This is usually just an ID of the product and the quantity they would like to purchase. Since it doesn't make sense for one user to purchase multiple copies of a course, we have hard-coded the quantity. ```jsx import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0' import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() const stripe = initStripe(process.env.STRIPE_SECRET_KEY) module.exports = withApiAuthRequired(async (req, res) => { const { courseId } = req.query const { user: { email }} = getSession(req, res) const user = await prisma.user.findUnique({ where: { email }, }) const course = await prisma.course.findUnique({ where: { id: parseInt(courseId) }, }) await prisma.$disconnect() const lineItems = [ { price_data: { currency: 'aud', // swap this out for your currency product_data: { name: course.title, }, unit_amount: course.price, }, quantity: 1, }, ] const session = await stripe.checkout.sessions.create({ customer: user.stripeId, payment_method_types: ['card'], line_items: lineItems, mode: 'payment', success_url: `${process.env.CLIENT_URL}/course/${course.slug}`, cancel_url: `${process.env.CLIENT_URL}/payment/cancelled`, payment_intent_data: { metadata: { userId: user.id, courseId, }, }, }) res.json({ id: session.id }) }) ``` So there is a bit going on in this example. 1. We need to know who the user is so this needs to be an authenticated API route. We're using `withApiAuthRequired()` to help us with that. 2. We get the course ID from the dynamic part of the URL. 3. We get the user's email from the session. The session contains session information from Auth0, but is missing things like their Prisma and Stripe ID. 4. We make a request to Prisma for the full user. 5. We make a request to Prisma for the full course. We don't want to trust the client to send us data about the course, just which one they would like to purchase. 6. We create an array of line items that the user would like to purchase. We are just charging for a single item, but this still needs to be an array for Stripe to process it. 7. We create a Stripe Checkout session with some information about the transaction and pass this back to the client so they can be redirected to Stripe. 8. We are attaching some metadata to the session - user ID and course ID. This will be used when we configure webhooks. ## Subscriptions Subscriptions are significantly more complex than one-off payments. We need to keep a track of when to charge the user again, as well as store their card details and deal with all the edge cases when they want to change to a different plan or cancel their subscription altogether. Thankfully, Stripe does all the hard work so we don't need to worry about any of this. We just create our different pricing options as products in the Stripe dashboard, and create an API route to initiate the session. ```jsx import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0' import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() const stripe = initStripe(process.env.STRIPE_SECRET_KEY) module.exports = withApiAuthRequired(async (req, res) => { const { priceId } = req.query const { user: { email }} = getSession(req, res) const user = await prisma.user.findUnique({ where: { email }, }) await prisma.$disconnect() const lineItems = [ { price: priceId, quantity: 1, }, ] const session = await stripe.checkout.sessions.create({ customer: user.stripeId, mode: 'subscription', payment_method_types: ['card'], line_items: lineItems, success_url: `${process.env.CLIENT_URL}/payment/success`, cancel_url: `${process.env.CLIENT_URL}/payment/cancelled`, metadata: { userId: user.id, }, }) res.json({ id: session.id }) }) ``` It is actually fewer lines of code than a one-off payment! Amazing! Now that we have payments implemented we probably need to tell our Prisma DB that someone has purchased a course or updated their subscription. ## Webhooks Webhooks allow us to subscribe to particular events, and have Stripe let us know when they happen. Let's create a new API route to handle this. ```jsx import initStripe from 'stripe' import { buffer } from 'micro' import { PrismaClient } from '@prisma/client' const stripe = initStripe(process.env.STRIPE_SECRET_KEY) const prisma = new PrismaClient() export const config = { api: { bodyParser: false } } export default async (req, res) => { const reqBuffer = await buffer(req) const signature = req.headers['stripe-signature'] const signingSecret = process.env.STRIPE_SIGNING_SECRET let event try { event = stripe.webhooks.constructEvent(reqBuffer, signature, signingSecret) } catch (err) { console.log(err) return res.status(400).send(`Webhook Error: ${err.message}`) } const { metadata } = event.data.object const stripeId = event.data.object.customer switch (event.type) { case 'charge.succeeded': if (metadata?.userId && metadata?.courseId) { const user = await prisma.user.update({ where: { id: parseInt(metadata.userId), }, data: { courses: { connect: { id: parseInt(metadata.courseId), }, }, }, }) } break case 'customer.subscription.created': if (stripeId) { await prisma.user.update({ where: { stripeId, }, data: { isSubscribed: true, }, }) } break case 'customer.subscription.updated': if (stripeId) { await prisma.user.update({ where: { stripeId, }, data: { isSubscribed: true, }, }) } break case 'customer.subscription.deleted': if (stripeId) { await prisma.user.update({ where: { stripeId, }, data: { isSubscribed: false, }, }) } break default: console.log(`Unhandled event type ${event.type}`) } await prisma.$disconnect() res.send({ received: true }) } ``` This one is a little complicated as the `req` object we get from Vercel is structured differently to what Stripe is expecting. Let's break it down. 1. We export a `config` object to tell Vercel we want the raw request. 2. We compare the request we get from the user with Stripe's `constructEvent` function. This validates that the request was sent by Stripe and returns the webhook event object. If it cannot validate the request, it throws an exception, and we return an error to the client. 3. Next we determine which event has been received - `charge.succeeded` - user purchased a course. - `customer.subscription.created` - user subscribed. - `customer.subscription.updated` - user has changed their subscription. Since cancellation events are triggered separately, we can just trust the user is still subscribed. - `customer.subscription.deleted` - user cancelled their subscription. This is triggered when the subscription expires, rather than when they cancel. 4. Update our Prisma user. Webhooks can be tested locally using [Stripe's CLI tool](https://stripe.com/docs/stripe-cli). [Check out this article from the Stripe docs](https://stripe.com/docs/webhooks/test) to get it setup. Prod webhooks can be setup in Stripe's dashboard. This is the interaction between our application, Stripe and Prisma when a user subscribes.  ## Customer portal The last thing we need to set up is a customer portal. This will enable users to manage their own subscription and payment information. This can be configured via Stripe's dashboard `Settings > Billing > Customer Portal` and gives super granular control over what you would like customers to be able to change. A new portal session can be initiated from an API route like this. ```jsx import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0' import initStripe from 'stripe' import { PrismaClient } from '@prisma/client' const stripe = initStripe(process.env.STRIPE_SECRET_KEY) const prisma = new PrismaClient() module.exports = withApiAuthRequired(async (req, res) => { const { user: { email }} = getSession(req, res) const user = await prisma.user.findUnique({ where: { email }, }) await prisma.$disconnect() const session = await stripe.billingPortal.sessions.create({ customer: user.stripeId, return_url: process.env.CLIENT_URL, }) res.send({ url: session.url, }) }) ``` By allowing users to manage this stuff directly with Stripe, we do not need to build these flows ourselves, and since we have subscribed to those webhooks, Stripe will just let us know if the user changes anything. # Final thoughts It is amazing standing on the shoulders of giants! These services are incredible! We have created a complex SaaS project with authentication and multiple payment options with a very minimal amount of code. This stack was a pleasure to work in and was almost seamless. Stripe is not only making this stuff a delight for developers to build hobby projects, t hey are also enabling people of all kinds to set up their own online businesses and make a living. Very cool! # Helpful resources - [Build a SaaS project with Stripe](https://jonmeyers.io/blog/build-a-saas-platform-with-stripe) by me! - [React 2025](https://react2025.com/) by Lee Robinson - [Minimum viable SaaS](https://github.com/jaredpalmer/minimum-viable-saas) By Jared Palmer - [nextjs-auth0 repo](https://github.com/auth0/nextjs-auth0) - [Calling external API from Auth0 Rule](https://community.auth0.com/t/how-do-i-call-my-api-from-a-rule/41309) - [Rules metadata in Auth0](https://auth0.com/docs/rules/metadata) - [Calling a rule after social login](https://community.auth0.com/t/calling-hook-for-social-login/35604) - [Stripe API docs](https://stripe.com/docs/api) - [Stripe webhook verification with Next.js](https://codedaily.io/tutorials/Stripe-Webhook-Verification-with-NextJS) - [Testing Stripe webhooks](https://stripe.com/docs/webhooks/test) <EmailSubscribeWidget />
lessonDuration 3m 53s
We'll create the template for our new page and set everything up so that we can use this page to create new tasks. The first thing we will do is create a BehaviorSubject task variable that we'll store form values in to send to Firebase. Because we are using the ionic framework we'll lean heavily into this when creating our templates. You'll see how we bind text values to the object we'll send to Firebase as well as a selector component that will use `ion-segment`. We'll also see a tip on handling the `async` pipe in a top container in our template so that we don't have to manually add it everywhere we'll render a property from an observable
lessonDuration 4m 3s
We have a new task form but currently it doesn't do anything. In this lesson we'll implement the save button that will add the task to Firebase. First, we'll create a reference to our tasks collection in Firestore, and then push a new document to that collection with the `addDoc` function Firestore provides us. After the document is in the database, we'll use the `updateDoc` function to edit that document and add the document's ID as a property on the document.
lessonDuration 3m 44s
We'll navigate our users to a task's detail page. To do so we want to reuse the task page that we built for creating new tasks. The difference here is we'll check the route if it includes a task Id, if it does we will grab that task from our database. To do this we will use Angular's `ActivatedRoute` class in the `ngOnInit` lifecycle method to decide when to show the form for creating a new task, and when to populate it with an existing task's data. Firebase gives us a handy `docData` function that we can access the task data via the id and subscribe to it.
lessonDuration 2m 25s
Now that we have users in our application, we need to start associating them with tasks that are created. We'll revisit our task object and add our currently logged-in user's ID to our task object so that we can show users only their tasks. This is done through the Firebase Auth module.
lessonDuration 2m 51s
Now that tasks are actually associated with a user in our database, we want to only show a user their own tasks. To do this we'll revisit our task list and make some changes to use the `query()` and `where()` methods to filter our list before we get it from the database. We'll learn how to pass our user's ID to a query and fetch only the tasks that belong to that user. Because Firebase uses Observables, you'll also see how we handle and change observables in Angular.
lessonDuration 2m 37s
Learn how to connect the Firestore emulator and explore it further in the Firebase Emulator Suite.
talk
As the costs associated with software development continue to increase, companies & developers are looking for ways to increase their efficiency & do more with their existing skillset. Meanwhile, in the serverless movement, there has been an evolution in the way companies think about the way they are building applications, reducing the initial cost of development by taking advantage of managed services like Auth0, Cloudinary, Firebase, & AWS Lambda instead of building & maintaining their own servers & service implementations. When people speak about serverless, they typically tend to think about a collection of functions calling each other when in reality the best serverless applications consist of thick client code handling all interaction logic, heavy use of managed services & small glue functions to fill in the missing pieces. In this talk, I’ll introduce a workflow that allows front end developers to build full stack applications using JavaScript by taking advantage of managed services, implementing real-world features like authentication, managed GraphQL APIs, serverless Lambda functions, & chatbots using a CLI based workflow.