Supabase Dashboard Settings
Create Next App @latest
Typescriptなし / Page Router / srcディレクトリ使用 / @エイリアスなし
Create Supabase Account
SupabaseはPostgreSQLを使っています
Create Table
products table
COLUMN NAME | TYPE | DEFAULT VALUE | |
id | int8 | image_url | jsonb |
name | text | quantity | int8 |
description | text | created_at | timestamptz |
price | int8 | ||
user | text |
(※1 … JsonbはJsonより検索やフィルタリングが高速でありPostgreSQLで推奨されています)
(※2 … timestampではなくtimestamptxをSupabaseが推奨します)
profiles table
COLUMN NAME | TYPE | DEFAULT VALUE | |
id | int8 | ||
uid | text | ||
name | text | ||
bio | text | ||
created_at | timestamptz | now() |
users table
supabaseの認証システムを使うと、ダッシュボードのAuthenticationにUsersテーブルが自動作成されます(手動でテーブルを作る必要はありません)
comments table
COLUMN NAME | TYPE | DEFAULT VALUE | |
id | int8 | ||
product | int8 | ||
comment | text | ||
user | text | ||
created_at | timestamptz | now() |
Table Policy Definition
このとき、Authentication > Policies から「Create policy」をクリックして、Templatesの「Enable read access for all uses」を選択して「Save Policy」します
profiles table … insert / select / update
CREATE POLICY "Allow all users to insert"
ON products
FOR INSERT
WITH CHECH (true);
SupabaseにはデフォルトでRLSというアクセス制限がかかっており、ポリシーが不十分だと次のようなエラーが出ます
Supabase Storage Upload Error: {
statusCode: '403',
error: 'Unauthorized',
message: 'new row violates row-level security policy'
}
Create Storage Bucket
無料枠はアップロード50MB、容量1GBまでです
Bucket Name : productBucket
Public Bucket : on (Public Access Allow)
Folder Name: products
Storage Policy (RowLevelSecurity)
bucket_id = 'productBucket'::text AND
storage.extension(name) IN ('jpg', 'png', 'webp') AND <--- 複数の拡張子をアップロード可能にします
lower((storage.foldername(name))[1]) = 'products' <-- publicからproductsにフォルダ名を変更します
auth.role() = 'anon' <-- 不特定ユーザーにこの権限roleを付与します
CONFIGURATION > Policies > New Policy > Get Started Quickly >
Template ; Allow access to JPG images in a public folder to anonymous users
Allowed Option : 全てにチェック [SELECT] [INSERT] [UPDATE] [DELETE]
Install Library
npm install @supabase/supabase-js
npm install formidable <--- nodejsでmultipartフォームデータを使う場合に必要です
package.jsonに@supabase/supabase-jsが追加されます
.env.local
NEXT_PUBLIC_SUPABASE_URL=[SupabaseのURL] <--- ダッシュボードのHomeの「プロジェクトのURL」をコピペ
NEXT_PUBLIC_SUPABASE_ANON_KEY=[SupabaseのAPIキー] <--- ダッシュボードのHomeの「APIキー」をコピペ
src/lib/supabase.js
imoprt { createClient } from '@supabase/supabase-js';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
export default supabase;