Building Production-Grade Web Applications with Supabase

Book description

Craft resilient web applications with Supabase by leveraging advanced features such as authentication, data and user management, and seamless AI integration using its powerful Postgres infrastructure

Key Features

  • Learn how to integrate Supabase and Next.js to create powerful and scalable web apps
  • Explore real-world scenarios with a multi-tenant ticket system
  • Master real-time data handling, secure file storage, and application security enhancement, while discovering the full potential of the database beyond holding data
  • Purchase of the print or Kindle book includes a free PDF eBook

Book Description

Discover the powerful capabilities of Supabase, the cutting-edge, open-source platform flipping the script on backend architecture. Guided by David Lorenz, a battle-tested software architect with over two decades of development experience, this book will transform the way you approach your projects and make you a Supabase expert.

In this comprehensive guide, you'll build a secure, production-grade multi-tenant ticket system, seamlessly integrated with Next.js. You’ll build essential skills for effective data manipulation, authentication, and file storage, as well as master Supabase's advanced capabilities including automating tasks with cron scheduling, performing similarity searches with artificial intelligence, testing your database, and leveraging real-time updates.

By the end of the book, you'll have a deeper understanding of the platform and be able to confidently utilize Supabase in your own web applications, all thanks to David's excellent expertise.

What you will learn

  • Explore essential features for effective web app development
  • Handle user registration, login/logout processes, and user metadata
  • Navigate multi-tenant applications and understand the potential pitfalls and best practices
  • Discover how to implement real-time functionality
  • Find out how to upload, download, and manipulate files
  • Explore preventive measures against data manipulation and security breaches, ensuring robust web app security
  • Increase efficiency and streamline task automation through personalized email communication, webhooks, and cron jobs

Who this book is for

This book is for developers looking for a hassle-free, universal solution to building robust apps using Supabase and its integration libraries. While a basic understanding of JavaScript is useful, it’s not essential as the book focuses on Supabase for creating high-performance web apps using Next.js. Experienced professionals from non-JavaScript backgrounds will find this book useful. Familiarity with Postgres, although helpful, is not mandatory as the book explains all the SQL statements used.

Table of contents

  1. Building Production-Grade Web Applications with Supabase
  2. Foreword
  3. Contributors
  4. About the author
  5. About the reviewers
  6. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Conventions used
    6. Get in touch
    7. Join Us on Discord
    8. Share Your Thoughts
    9. Download a free PDF copy of this book
  7. Part 1:Creating the Foundations of the Ticket System App
  8. Chapter 1: Unveiling the Inner Workings of Supabase and Introducing the Book’s Project
    1. Technical requirements (and some preamble)
    2. Understanding why Supabase is the stack you want
    3. Demystifying the inner workings of Supabase with Postgres
      1. Access logic within a route
      2. Access logic as a central service
      3. How Supabase handles access control
      4. How the access system works under the hood
    4. Supabase Studio – the convenient web dashboard
    5. Supabase Auth (GoTrue) – the authentication handler
    6. PostgREST – a REST and GraphQL API for your database
    7. Realtime – elevating the user experience
    8. Storage – simple and scalable object storage
    9. Image Proxy – helping to transform images on the fly
    10. Edge Functions – completing the optimization stack
    11. pg-meta – an internal helper service for the database
    12. Kong – the overarching service orchestrator
    13. Introducing the production-grade ticket system project
    14. Summary
  9. Chapter 2: Setting Up Supabase with Next.js
    1. Technical requirements
    2. Getting ready with Next.js
    3. Installing the Supabase CLI
    4. Running your first Supabase instance on your machine
      1. Initializing a new local Supabase instance
      2. Starting your first Supabase instance
    5. Managing multiple local Supabase instances
      1. Option 1 – the start-stop technique
      2. Option 2 – change ports
    6. Connecting to Supabase with the Supabase JavaScript client
      1. Initializing and testing the base Supabase JavaScript client within Next.js
      2. Understanding the base Supabase client
      3. Using the Supabase client with Pages Router and App Router
    7. Connecting directly to the database
    8. Using Supabase with TypeScript
    9. Connecting Supabase to other frameworks
      1. Nuxt 3
      2. Python
    10. Summary
  10. Chapter 3: Creating the Ticket Management Pages, Layout, and Components
    1. Technical requirements
    2. Setting up Pico.css with Next.js
    3. Building the login form
    4. Visualizing the Ticket Management UI
    5. Creating a shared UI layout with navigation elements
    6. Designing the Ticket List page
    7. Constructing the Ticket Details page
      1. Adding the comments section to the ticket details
    8. Implementing a page to create a new ticket
    9. Implementing a user overview
    10. Enhancing the navigation component
    11. Summary
  11. Part 2: Adding Multi-Tenancy and Learning RLS
  12. Chapter 4: Adding Authentication and Application Protection
    1. Technical requirements
    2. Adding authentication protection with Supabase
      1. Creating users
      2. Preparing the middleware for authentication
      3. Implementing the login functionality in our app
      4. Protecting access to the Ticket Management system
    3. Adding a log out button
      1. Logging out using the frontend
      2. Logging out using the backend
    4. Understanding server authentication
    5. Enhancing the password login
    6. Authenticating with magic links
      1. Sending magic links with signInWithOtp() on the frontend
      2. Why I usually don’t use signInWithOtp()
      3. Understanding a server-only magic link flow
      4. Implementing a server-only magic link flow with custom email content
    7. Adding password recovery
    8. Learning about the Site URL and redirect URLs
      1. How to configure site and redirect URLs
    9. Optional knowledge: adapting built-in templates
    10. Summary
  13. Chapter 5: Crafting Multi-Tenancy through Database and App Design
    1. Technical requirements
    2. What kind of multi-tenancy do we need?
    3. Designing the database for multi-tenancy
      1. Planning our database
      2. Creating the tenants table
      3. Designing the users table
      4. Designing the permission structure
    4. Committing your database state (if you don’t seed it, you lose it)
    5. Making our Next.js application tenant-aware
      1. Enhancing the middleware to safeguard dynamic routes
      2. Fixing all static routes in the application
      3. Making the login tenant-based
    6. Summary
  14. Chapter 6: Enforcing Tenant Permissions with RLS and Handling Tenant Domains
    1. Technical requirements
    2. Learning to work with RLS
      1. Fetching tenant data with the restrictive Supabase client
      2. Defining RLS policies to access tenants based on permissions
      3. Creating a permission-based RLS policy
      4. Understanding and solving RLS implications
      5. Shrinking RLS policies based on the implications
      6. Learning about RLS implications
    3. Minimizing RLS complexity with custom claims
      1. Extending app_metadata with tenant permissions
      2. Keeping custom claims in sync with the table data
    4. Making the authentication process tenant-based
      1. Preventing password login on a foreign tenant
      2. Preventing the magic link login for foreign tenants
      3. Rejecting to visit invalid and forbidden tenant URLs when signed in
    5. Matching a tenant per domain instead of per path
      1. Adding custom domains via the hosts file
      2. Mapping domains in our application
      3. Bringing back localhost with mapped domains
    6. Summary
  15. Chapter 7: Adding Tenant-Based Signups, including Google Login
    1. Technical requirements
    2. Understanding the impact of disabling signups
      1. Disabling signups generally
      2. Disabling specific signup methods
    3. Implementing the registration page
    4. Processing the registration with a Route Handler
      1. Reading and validating the form data
      2. Rejecting registration
      3. Handling account creation
      4. Adding the service user and permission rows
      5. Sending the activation email
      6. Redirecting the user to a success page
    5. Enabling OAuth/Sign-in with Google
      1. Obtaining Google OAuth credentials
      2. Configuring our Supabase instance with the OAuth credentials
      3. Adding a “Sign in with Google” option triggering the OAuth process
      4. Solving the crypto/HTTPS security problem
      5. Building a verification route to finalize the registration
    6. Dealing with invalid user registration
    7. Summary
  16. Part 3: Managing Tickets and Interactions
  17. Chapter 8: Implementing Dynamic Ticket Management
    1. Technical requirements
    2. Creating the tickets table in the database
    3. Creating tickets and using triggers
      1. Implementing the ticket creation logic
      2. Using triggers to derive and set the user ID
      3. Improving loading behavior after adding a ticket
      4. Enforcing checks on the database columns
    4. Viewing the ticket details
      1. Caching the author’s name with a trigger
      2. Improving the date and status view
    5. Listing and filtering tickets
      1. Enabling paging
      2. Sorting tickets
      3. Creating a ticket filter
    6. Deleting tickets
    7. Summary
  18. Chapter 9: Creating a User List with RPCs and Setting Ticket Assignees
    1. Technical requirements
    2. Adding a user list with an RPC
      1. Ensuring there are enough users to test
      2. Enhancing the table structure
      3. Fetching the users with an RPC
      4. Using the function with an RPC
    3. Allowing the setting and editing of an assignee to a ticket
      1. Adding assignee columns in the tickets table
      2. Creating the trigger function to cache the name
      3. Adding an assignee at ticket creation
      4. Showing the assignee in the details
      5. Updating the assignee
    4. Summary
  19. Chapter 10: Enhancing Interactivity with Realtime Comments
    1. Technical requirements
    2. Creating the comments table
    3. Adding a trigger to set the tenant automatically
    4. Adding and optimizing RLS policies
      1. Creating RLS helper functions
      2. Creating the policies
    5. Implementing comment creation
    6. Listing existing comments from the server
    7. Implementing Realtime comments
      1. Enabling Realtime and subscribing to it
      2. Updating the UI with Realtime data
      3. Triggering impersonated real-time updates with the Table Editor
    8. Embracing additional Realtime insights and learning about potential pitfalls
    9. Summary
  20. Chapter 11: Adding, Securing, and Serving File Uploads with Supabase Storage
    1. Technical requirements
    2. Creating and understanding Storage buckets
      1. Examining public buckets
      2. Exploring files within a bucket programmatically
      3. Learning how a basic RLS policy can be added to your bucket
      4. Understanding private buckets and revising our bucket choice
      5. Choosing a private or a public bucket?
    3. Enabling the addition of comments with file attachments
      1. Preparing the UI with file upload possibility
      2. Uploading files to storage
      3. Connecting uploaded files with the written comment
      4. Showing the connected files
    4. Serving image attachments directly in the UI
      1. Using Image Transformations
      2. Building a pseudo-CDN for private buckets
      3. Using the pseudo-CDN inside our UI
    5. Writing RLS policies directly on buckets and objects table
    6. Diving into advanced storage restrictions
    7. Summary
  21. Part 4: Diving Deeper into Security and Advanced Features
  22. Chapter 12: Avoiding Unwanted Data Manipulation and Undisclosed Exposures
    1. Technical requirements
    2. Understanding PostgREST’s OpenAPI Schema exposure
      1. Preventing schema exposure
      2. Removing schemas from usage via API
      3. Specifically exposing a schema to the API
    3. Being careful with current_user usage and understanding auth.role()
    4. Generating new Anonymous Keys, Service Role Keys, and database passwords
    5. Benefiting from Supabase Vault
      1. Creating secrets in the Vault and reading them
      2. Using the secret in the business logic/within your application
    6. Utilizing silent resets to avoid data manipulation
    7. Enabling column-level security/working with roles
    8. Understanding security on views and manually created tables
    9. Changing the max_rows configuration
    10. Understanding safe-guarded API updates or deletion
    11. Adding middleware inside Postgres for each API request
      1. Adding middleware for PostgREST
    12. Using the Security Advisor
    13. Allowing a listing of IPs for database connections
    14. Enforcing SSL on direct database connections
    15. Summary
  23. Chapter 13: Adding Supabase Superpowers and Reviewing Production Hardening Tips
    1. Technical requirements
    2. Making sense of search_path
      1. Comprehending search path in Postgres
      2. Grasping the importance of extra_search_path
    3. Familiarizing yourself with database extensions
      1. Installing an extension in the default extensions schema
      2. Installing extensions in their own schema
      3. Using the programmatic installation of extensions versus using the UI
    4. Adding an AI-based semantic ticket search
      1. Deciding on an embeddings provider
      2. Creating the embeddings column in the table
      3. Creating embeddings with OpenAI
      4. Comparing embeddings to find matching search results
    5. Using anonymous sign-ins
    6. Transforming external APIs into tables with foreign data wrappers
    7. Using webhooks
      1. Creating webhooks with dynamic URLs per environment
    8. Understanding Edge Functions
      1. Understanding when to use Edge Functions
      2. Creating an Edge Function that runs for new rows
      3. Triggering the Edge Function
    9. Using cronjobs to notify about due tickets
    10. Using pg_jsonschema for JSON data integrity
    11. Testing the database with pgTAP
    12. Setting the auth.storageKey to avoid migration problems
    13. Extending supabase.ts with custom typings
    14. Improving RLS and query performance
    15. Identifying database performance problems and bloat
    16. Working with complex table joins
    17. Reviewing the underestimated benefit of using an external database client
    18. Understanding migrations
    19. Utilizing database branching
    20. Disabling GraphQL or PostgREST (if you don’t need it)
    21. Using a dead-end built-in mailing setup
    22. Retrieving table data with the REST API and cURL
    23. Summary
  24. Index
    1. Why subscribe?
  25. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share Your Thoughts
    3. Download a free PDF copy of this book

Product information

  • Title: Building Production-Grade Web Applications with Supabase
  • Author(s): David Lorenz
  • Release date: August 2024
  • Publisher(s): Packt Publishing
  • ISBN: 9781837630684