iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👀

Setting Up a Local Development Environment for Supabase

に公開
1

Supabase notes on setting up a local development environment. Recommended at the start of a project.

Preface

Supabase provides a mechanism to set up an environment identical to their production environment locally using Docker. When you start this up locally, you can use a GUI called Studio (the same one as in production). However, only PostgreSQL-related features (Database, Table/SQL Editor, etc.) can be operated from Studio. Storage, Auth, and Settings provided in production do not appear in the local Studio. They are reportedly on the roadmap but have not been provided yet.

Creating a Supabase Project

Create a project in Supabase by referring to Introduction | Supabase. Simply log in with GitHub and create any project for now. You can change it as much as you want later.

Local Environment Setup

The following assumes that you have already initialized your project using Next.js, Nuxt.js, etc., and have executed cd your-app-project. It is generally best to proceed according to Local Development | Supabase.

Installing the CLI

First, install the Supabase CLI. Since I am on a Mac, I installed it using brew install supabase/tap/supabase.

Preparing to Use Supabase

Run supabase init in the root directory of your application.

 $ supabase init

This will generate a supabase/ directory. It contains supabase/migrations and supabase/config.toml. As the names suggest, these are the migration files and the file describing Supabase configurations.

[If Necessary] Linking Remote DB and Local DB

Linking the remote DB (the project in Supabase you created first) and the local DB allows you to sync the remote environment's DB schema to your local environment. You will also be able to push migrations from local to remote. It is helpful to refer to cli/examples/tour at main · supabase/cli.

First, set the remote DB information locally. This should create a .env file under the supabase/ directory. Make sure to add it to your .gitignore.

 $ supabase db remote set 'postgresql://postgres:<YOUR_DB_PASSWORD>@db.<YOUR_PROJECT_REF>.supabase.co:5432/postgres'

Then, run the following command. This will bring the schema information from the remote DB to your local environment. SQL files should be generated under supabase/migration.

 $ supabase db remote commit

Starting Supabase

Let's try starting the Supabase local environment.

 $ supabase start
 Started local development setup.

          API URL: http://localhost:54321
           DB URL: postgresql://postgres:postgres@localhost:54322/postgres
       Studio URL: http://localhost:54323
         anon key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.ZopqoUt20nEV9cklpv9e3yw3PVyZLmKs5qLD6nGL1SI
 service_role key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIn0.M2d2z4SFn5C7HlJlaSLfrzuYim9nbY_XI40uWFN3hEE

This command will install and start everything necessary for the Supabase environment using Docker. The initial setup takes about 5 minutes. Once finished, local URLs and API keys will be generated. The key values seem to be fixed, so it might be a good idea to register them once in a file like .env.local.

Accessing http://localhost:54323/ will display the familiar Supabase Dashboard page.

Note: If an error occurs with supabase start

If you brought the schema from the remote DB using supabase db remote commit, the execution order of those SQL statements might be incorrect. The SQL statements generated by this command are merely a snapshot of the current DB schema. For example, if you performed operations in the remote GUI like creating a table called tags, then creating a table called articles, and setting a foreign key from tags to articles. The generated SQL statements would look like: SQL for tags and its foreign key constraint first, followed by SQL for articles. However, in this case, a reference to articles occurs within the foreign key creation SQL for tags before articles is even created. Therefore, an error occurs. In SQL terms, it looks something like this. You'll have to fix this manually...

init.sql
 CREATE TABLE IF NOT EXISTS public.tags
 (
   id uuid NOT NULL,
   article_id bigint NOT NULL,
   CONSTRAINT tags_article_id_fkey FOREIGN KEY (article_id)
           REFERENCES public.articles (id) MATCH SIMPLE  -- <- articles has not been created yet!!
           ON UPDATE NO ACTION
           ON DELETE NO ACTION,
 )

 CREATE TABLE IF NOT EXISTS public.articles
 (
 ....

Subsequent Flow

When you change the DB schema locally, running the following command will generate a migration file. You don't have to write the SQL statements yourself. It handles table changes made via the GUI appropriately on the command-line side.

 $ supabase db commit <migration_file_prefix_name>

You can reflect the changes in the production DB by running the following command at the right time.

 $ supabase db push

Others

Initial Data

Regarding initial data, if you create a supabase/seed.sql as shown below, it will be executed every time you run supabase start.

supabase/seed.sql
 -- in supabase/seed.sql
 INSERT INTO boarders(id, name) VALUES (1, 'Arthur Dent'), (2, 'Ford Prefect');

Reset

You can reset the local DB with the following. This is useful when you want to redo migrations from scratch.

 $ supabase db reset

For other commands, you should refer to the following link:
supabase help | Supabase

JS Client

Since you will likely use it anyway, it's a good idea to install the JavaScript client as well.

 $ npm install --save @supabase/supabase-js

Generating Table Type Information

Install openapi-typescript to generate types from the schema information. Converting camelCase to snake_case is also covered in the following link:

When Local and Remote Migrations Get Out of Sync

If you modify local migration files, they might accidentally become inconsistent with the remote migrations. In this case, the quickest way is to delete the local migration files, delete all records from the remote supabase_migrations.schema_migrations with delete from supabase_migrations.schema_migrations;, and then relink the remote and local DBs using supabase db remote commit. Alternatively, you can carefully delete records in supabase_migrations.schema_migrations one by one to match the local state.

Using Third-Party OAuth Provider Authentication Locally

Update: 2022/3/2

Someone inside who saw the PR I sent regarding this issue provided a fundamental solution. Specifically, running supabase init now generates a config.toml file, where you can configure External auth providers. This allows the use of third-party OAuth providers even in a local environment.
https://github.com/supabase/cli/pull/172

Due to this update, the following description is no longer necessary.

Old content

By the way, I'm not sure if this is the correct way, but currently, if you want to use third-party OAuth provider authentication features with the CLI in a local environment, a rather irregular method is required. You can manage this by adding your preferred environment variables to the GoTrue settings in internal/start/start.go of the supabase/cli: Supabase CLI and then performing a go build.

By looking at gotrue/example.env at master · supabase/gotrue in the GoTrue code, which handles Supabase's Authentication, you can see what kind of environment variables can be added. Refer to it as needed. An example flow is as follows. I've added comments inside the code.

 // Go to an appropriate location
 $ cd /Users/hoge/dev

 // Download supabase-cli
 $ git clone git@github.com:supabase/cli.git
 $ cd cli/

 // Rewrite source code
 $ vim internal/start/start.go
 ...
 env := []string{
 	"API_EXTERNAL_URL=http://localhost:" + utils.ApiPort,

 	"GOTRUE_API_HOST=0.0.0.0",
 	"GOTRUE_API_PORT=9999",

 	"GOTRUE_DB_DRIVER=postgres",
 	"GOTRUE_DB_DATABASE_URL=postgresql://supabase_auth_admin:postgres@" + utils.DbId + ":5432/postgres",

 	"GOTRUE_SITE_URL=http://localhost:3000",
 	"GOTRUE_DISABLE_SIGNUP=false",

 	"GOTRUE_JWT_SECRET=super-secret-jwt-token-with-at-least-32-characters-long",
 	"GOTRUE_JWT_EXP=3600",
 	"GOTRUE_JWT_DEFAULT_GROUP_NAME=authenticated",

 	"GOTRUE_EXTERNAL_EMAIL_ENABLED=true",

 	"GOTRUE_EXTERNAL_PHONE_ENABLED=true",
 	"GOTRUE_SMS_AUTOCONFIRM=true",

 	// Custom settings for Google OAuth2. 
	// You can add info for any third party like FACEBOOK or TWITTER here.
 	"GOTRUE_EXTERNAL_GOOGLE_ENABLED: 'true'",
	"GOTRUE_EXTERNAL_GOOGLE_CLIENT_ID: XXXXXXXXXX.apps.googleusercontent.com",
	"GOTRUE_EXTERNAL_GOOGLE_SECRET: XXXXX-XXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
	"GOTRUE_EXTERNAL_GOOGLE_REDIRECT_URI=http://localhost:3000/auth/v1/callback",
	"GOTRUE_EXTERNAL_URI=https://accounts.google.com"
 }
....

// This is the build for macOS. For Windows, etc., change the GOOS and GOARCH parts.
// Since naming the command generated by the build "supabase" might conflict with the official CLI, I'm naming it "tupabase" arbitrarily.
$ GOOS=darwin GOARCH=amd64 go build -o build/tupabase .

// Move to the root of the project where you want to use supabase
$ cd /Users/hoge/dev/my-project

// The supabase command should be executable. If an error occurs, try deleting supabase/.branches or supabase/.temp and try again.
$ /Users/hoge/dev/cli/build/tupabase init
$ /Users/hoge/dev/cli/build/tupabase start

After that, feel free to add the generated /Users/hoge/dev/cli/build/tupabase to your PATH or use it as you like.

https://scrapbox.io/files/61e00ad85a5677001f95c049.png
Also, don't forget to register http://localhost:54321/auth/v1/callback as the redirect or callback URL on the OAuth provider's site (such as the GCP OAuth client configuration screen for Google).

In the Supabase environment deployed locally by the CLI, the defaults are http://localhost:54321 for the API, http://localhost:54322 for the DB, and http://localhost:54323 for Studio. Additionally, your frontend is likely running at http://localhost:3000. By the way, the URL redirected to after authentication at /auth/v1/callback returns to http://localhost:3000 by default. This is because GOTRUE_SITE_URL=http://localhost:3000 is set in GoTrue.

Link

Discussion

Sonia LiangSonia Liang

(このコメントは投稿主及びこの記事に辿った人への参考情報。)

supabase を始めてみようとこのページに辿りました。
そんな古くない投稿なのに、なぜか example/tour へのリンク切れが発生しています。

調べてみたら、ちょうど19日前に、supabase 側が色々と更新をかけていました。

https://github.com/supabase/cli/commit/273f2668bb518df607ef5bf180e4af0d1f120655

上記の情報によると、example/tour だったものは、以下の公式ガイドに移ったそうです。

https://supabase.com/docs/guides/local-development