Building Production-Grade Web Applications with Supabase - David Lorenz - E-Book

Building Production-Grade Web Applications with Supabase E-Book

David Lorenz

0,0
28,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 664

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Building Production-Grade Web Applications with Supabase

A comprehensive guide to database design, security, real-time data, storage, multi-tenancy, and more

David Lorenz

Building Production-Grade Web Applications with Supabase

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kaustubh Manglurkar

Publishing Product Manager: Chayan Majumdar

Book Project Manager: Sonam Pandey

Senior Editor: Hayden Edwards

Technical Editor: K Bimala Singha

Copy Editor: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Jyoti Kadam

DevRel Marketing Coordinator: Anamika Singh and Nivedita Pandey

First published: August 2024

Production reference: 1260724

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83763-068-4

www.packtpub.com

To my spouse, Ella, for her endless support and love. To my mother and sister for their understanding. To Alexander Hachmann for the time provided. To Christoph Kolb for the support. To Kai Klostermann for being my best friend and supporter. To the Supabase team for providing me with their trust, help, and warm words.

– David Lorenz

Foreword

Six years ago, I joined Mercedes-Benz.io, the company where David worked, and I had the privilege of collaborating with him for four years. It quickly became evident that he was a “beacon” developer—a professional others admired for his exceptional skills and leadership.

David’s passion for knowledge is unparalleled. He eagerly explores the latest technological advancements, conducting thorough research on each topic to form well-founded conclusions. His dedication to understanding the intricacies of his craft sets him apart as a truly exceptional professional.

As lead developers for our respective teams on the same project, we faced unique challenges. Our project had specific constraints, chief among them a commitment to the old-fashioned approach of vanilla JavaScript.

“So what?”, you might ask. And it’s a fair question.

In an industry where cutting-edge frontend frameworks reign supreme, our approach was akin to building a house with hand tools while others used power equipment. We often had to solve complex problems from the ground up, without the shortcuts and conveniences modern toolsets provide. This wasn’t just about writing code—it was about rediscovering and applying core principles that many developers had begun to take for granted.

Moreover, our role extended beyond coding. We became mentors and educators, guiding our colleagues through the intricacies of framework-free development. This meant teaching not just how to solve problems, but why certain solutions worked, fostering a deeper understanding of fundamental concepts.

It was in this challenging environment that David’s exceptional qualities truly shone. From the early days of my tenure, his ability to form and share strong, well-researched opinions on a wide range of topics became apparent. David didn’t just know the how; he understood the why, and he had a knack for explaining both clearly and concisely. His enthusiasm for sharing these insights is a core part of who he is—a trait you, dear reader, are about to experience firsthand through this book.

In our fast-paced technological landscape, where the “flavor of the month” changes constantly and documentation often lags behind, individuals such as David are invaluable. They serve as anchors amidst the turbulent sea of evolving technologies, helping others navigate and understand the ever-changing currents. David’s ability to provide clarity and insight where it’s needed most isn’t just useful—it’s essential for staying ahead in our field.

This book offers you a glimpse into the same level of insight and enthusiasm that David brought to our team every day, distilled into a format that’s accessible and practical for developers at all levels. Regardless of your current expertise with Supabase, this book promises to be a valuable resource. David provides the following:

Clear explanations covering essential aspects of SupabasePractical guidance on integrating Supabase into your projectsStrategies for building performant and scalable applicationsInsights on how Supabase can compete with more expensive solutions

Throughout these pages, you’ll find David’s knowledge translated into actionable insights. Whether you’re new to Supabase or an experienced developer, this book aims to enhance your understanding and application of Supabase, empowering you to create robust, efficient, and cost-effective solutions.

Jorge Varandas

System Architect, Mercedes-Benz.io

Contributors

About the author

David Lorenz is a web software architect and lecturer who began programming at age 11. Before completing university in 2014, he had built a CRM system that automated an entire company and worked with numerous agencies through his own company. In 2015, he secured his first employment as a senior web developer, where he played a pioneering role in using cutting-edge technology and was an early adopter of progressive web apps. In 2017, he became the leading frontend architect and team lead for one of the largest projects at Mercedes-Benz.io, involving massive-scale architecture. Today, David provides valuable insights and guidance to clients across various industries, using his extensive experience and exceptional problem-solving abilities.

I want to thank the people who have been close to me and supported me, especially Ella and the team at Wahnsinn Design GmbH, as well as my mom and my sister.

About the reviewers

Kamil Pyrkosz is a multiplatform programmer who fell in love with Supabase the first time he used it, surprised by how easy and powerful it was. His passion for Supabase resulted in the creation of a YouTube channel, Kamil the Supabase enjoyer, where he makes Supabase tutorials and videos on other related topics.

Thor (Thorsten) Schaeff is a software developer, startup advisor, and Angel investor. Having grown up around the SAP headquarters in Germany, he started building websites back in high school, later studied computer science and media, and interned with Google in London. He joined early Stripe in Dublin, building out various user-facing engineering teams across Europe and Southeast Asia, contributing to open source software, and mentoring and investing in early-stage startups along the way.

Now settled in sunny Singapore, Thor works on DevRel and DX at Supabase, helping developers take advantage of the power of Postgres.

We would also like to thank Jorge Varandas, Kai Klostermann, and Kushal Seth for their help in reviewing the book.

Table of Contents

Preface

Part 1: Creating the Foundations of the Ticket System App

1

Unveiling the Inner Workings of Supabase and Introducing the Book’s Project

Technical requirements (and some preamble)

Understanding why Supabase is the stack you want

Demystifying the inner workings of Supabase with Postgres

Access logic within a route

Access logic as a central service

How Supabase handles access control

How the access system works under the hood

Supabase Studio – the convenient web dashboard

Supabase Auth (GoTrue) – the authentication handler

PostgREST – a REST and GraphQL API for your database

Realtime – elevating the user experience

Storage – simple and scalable object storage

Image Proxy – helping to transform images on the fly

Edge Functions – completing the optimization stack

pg-meta – an internal helper service for the database

Kong – the overarching service orchestrator

Introducing the production-grade ticket system project

Summary

2

Setting Up Supabase with Next.js

Technical requirements

Getting ready with Next.js

Installing the Supabase CLI

Running your first Supabase instance on your machine

Initializing a new local Supabase instance

Starting your first Supabase instance

Managing multiple local Supabase instances

Option 1 – the start-stop technique

Option 2 – change ports

Connecting to Supabase with the Supabase JavaScript client

Initializing and testing the base Supabase JavaScript client within Next.js

Understanding the base Supabase client

Using the Supabase client with Pages Router and App Router

Connecting directly to the database

Using Supabase with TypeScript

Connecting Supabase to other frameworks

Nuxt 3

Python

Summary

3

Creating the Ticket Management Pages, Layout, and Components

Technical requirements

Setting up Pico.css with Next.js

Building the login form

Visualizing the Ticket Management UI

Creating a shared UI layout with navigation elements

Designing the Ticket List page

Constructing the Ticket Details page

Adding the comments section to the ticket details

Implementing a page to create a new ticket

Implementing a user overview

Enhancing the navigation component

Summary

Part 2: Adding Multi-Tenancy and Learning RLS

4

Adding Authentication and Application Protection

Technical requirements

Adding authentication protection with Supabase

Creating users

Preparing the middleware for authentication

Implementing the login functionality in our app

Protecting access to the Ticket Management system

Adding a log out button

Logging out using the frontend

Logging out using the backend

Understanding server authentication

Enhancing the password login

Authenticating with magic links

Sending magic links with signInWithOtp() on the frontend

Why I usually don’t use signInWithOtp()

Understanding a server-only magic link flow

Implementing a server-only magic link flow with custom email content

Adding password recovery

Learning about the Site URL and redirect URLs

How to configure site and redirect URLs

Optional knowledge: adapting built-in templates

Summary

5

Crafting Multi-Tenancy through Database and App Design

Technical requirements

What kind of multi-tenancy do we need?

Designing the database for multi-tenancy

Planning our database

Creating the tenants table

Designing the users table

Designing the permission structure

Committing your database state (if you don’t seed it, you lose it)

Making our Next.js application tenant-aware

Enhancing the middleware to safeguard dynamic routes

Fixing all static routes in the application

Making the login tenant-based

Summary

6

Enforcing Tenant Permissions with RLS and Handling Tenant Domains

Technical requirements

Learning to work with RLS

Fetching tenant data with the restrictive Supabase client

Defining RLS policies to access tenants based on permissions

Creating a permission-based RLS policy

Understanding and solving RLS implications

Shrinking RLS policies based on the implications

Learning about RLS implications

Minimizing RLS complexity with custom claims

Extending app_metadata with tenant permissions

Keeping custom claims in sync with the table data

Making the authentication process tenant-based

Preventing password login on a foreign tenant

Preventing the magic link login for foreign tenants

Rejecting to visit invalid and forbidden tenant URLs when signed in

Matching a tenant per domain instead of per path

Adding custom domains via the hosts file

Mapping domains in our application

Bringing back localhost with mapped domains

Summary

7

Adding Tenant-Based Signups, including Google Login

Technical requirements

Understanding the impact of disabling signups

Disabling signups generally

Disabling specific signup methods

Implementing the registration page

Processing the registration with a Route Handler

Reading and validating the form data

Rejecting registration

Handling account creation

Adding the service user and permission rows

Sending the activation email

Redirecting the user to a success page

Enabling OAuth/Sign-in with Google

Obtaining Google OAuth credentials

Configuring our Supabase instance with the OAuth credentials

Adding a “Sign in with Google” option triggering the OAuth process

Solving the crypto/HTTPS security problem

Building a verification route to finalize the registration

Dealing with invalid user registration

Summary

Part 3: Managing Tickets and Interactions

8

Implementing Dynamic Ticket Management

Technical requirements

Creating the tickets table in the database

Creating tickets and using triggers

Implementing the ticket creation logic

Using triggers to derive and set the user ID

Improving loading behavior after adding a ticket

Enforcing checks on the database columns

Viewing the ticket details

Caching the author’s name with a trigger

Improving the date and status view

Listing and filtering tickets

Enabling paging

Sorting tickets

Creating a ticket filter

Deleting tickets

Summary

9

Creating a User List with RPCs and Setting Ticket Assignees

Technical requirements

Adding a user list with an RPC

Ensuring there are enough users to test

Enhancing the table structure

Fetching the users with an RPC

Using the function with an RPC

Allowing the setting and editing of an assignee to a ticket

Adding assignee columns in the tickets table

Creating the trigger function to cache the name

Adding an assignee at ticket creation

Showing the assignee in the details

Updating the assignee

Summary

10

Enhancing Interactivity with Realtime Comments

Technical requirements

Creating the comments table

Adding a trigger to set the tenant automatically

Adding and optimizing RLS policies

Creating RLS helper functions

Creating the policies

Implementing comment creation

Listing existing comments from the server

Implementing Realtime comments

Enabling Realtime and subscribing to it

Updating the UI with Realtime data

Triggering impersonated real-time updates with the Table Editor

Embracing additional Realtime insights and learning about potential pitfalls

Summary

11

Adding, Securing, and Serving File Uploads with Supabase Storage

Technical requirements

Creating and understanding Storage buckets

Examining public buckets

Exploring files within a bucket programmatically

Learning how a basic RLS policy can be added to your bucket

Understanding private buckets and revising our bucket choice

Choosing a private or a public bucket?

Enabling the addition of comments with file attachments

Preparing the UI with file upload possibility

Uploading files to storage

Connecting uploaded files with the written comment

Showing the connected files

Serving image attachments directly in the UI

Using Image Transformations

Building a pseudo-CDN for private buckets

Using the pseudo-CDN inside our UI

Writing RLS policies directly on buckets and objects table

Diving into advanced storage restrictions

Summary

Part 4: Diving Deeper into Security and Advanced Features

12

Avoiding Unwanted Data Manipulation and Undisclosed Exposures

Technical requirements

Understanding PostgREST’s OpenAPI Schema exposure

Preventing schema exposure

Removing schemas from usage via API

Specifically exposing a schema to the API

Being careful with current_user usage and understanding auth.role()

Generating new Anonymous Keys, Service Role Keys, and database passwords

Benefiting from Supabase Vault

Creating secrets in the Vault and reading them

Using the secret in the business logic/within your application

Utilizing silent resets to avoid data manipulation

Enabling column-level security/working with roles

Understanding security on views and manually created tables

Changing the max_rows configuration

Understanding safe-guarded API updates or deletion

Adding middleware inside Postgres for each API request

Adding middleware for PostgREST

Using the Security Advisor

Allowing a listing of IPs for database connections

Enforcing SSL on direct database connections

Summary

13

Adding Supabase Superpowers and Reviewing Production Hardening Tips

Technical requirements

Making sense of search_path

Comprehending search path in Postgres

Grasping the importance of extra_search_path

Familiarizing yourself with database extensions

Installing an extension in the default extensions schema

Installing extensions in their own schema

Using the programmatic installation of extensions versus using the UI

Adding an AI-based semantic ticket search

Deciding on an embeddings provider

Creating the embeddings column in the table

Creating embeddings with OpenAI

Comparing embeddings to find matching search results

Using anonymous sign-ins

Transforming external APIs into tables with foreign data wrappers

Using webhooks

Creating webhooks with dynamic URLs per environment

Understanding Edge Functions

Understanding when to use Edge Functions

Creating an Edge Function that runs for new rows

Triggering the Edge Function

Using cronjobs to notify about due tickets

Using pg_jsonschema for JSON data integrity

Testing the database with pgTAP

Setting the auth.storageKey to avoid migration problems

Extending supabase.ts with custom typings

Improving RLS and query performance

Identifying database performance problems and bloat

Working with complex table joins

Reviewing the underestimated benefit of using an external database client

Understanding migrations

Utilizing database branching

Disabling GraphQL or PostgREST (if you don’t need it)

Using a dead-end built-in mailing setup

Retrieving table data with the REST API and cURL

Summary

Index

Other Books You May Enjoy

Part 1:Creating the Foundations of the Ticket System App

In the first part of this book, we will embark on the journey of building the foundations for your ticket management app. You’ll explore the basics of Supabase, set up your development environment, and create a user-friendly interface. This part is all about laying the groundwork and getting you ready for more complex features ahead, so let’s dive in and start building!

This part includes the following chapters:

Chapter 1, Unveiling the Inner Workings of Supabase and Introducing the Book’s ProjectChapter 2, Setting Up Supabase with Next.jsChapter 3, Creating the Ticket Management Pages, Layout, and Components