6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

supabaseで簡単なTodoアプリを構築した話 - 0からフロント側の設定まで

Last updated at Posted at 2022-11-24

はじめに

Baas(Backend As A Service)で何かサービスを構築してみたいと思い、
firebaseを触ってみようと思ったところ、Firebase の代替と謳われているsupabaseを発見。

こちらの方が面白そうだと感じたため、構築してみることに

使ったもの

  • Vite + Svelte + Typescript

    • @supabase/supabase-js
    • tailwind css
  • supabase

    • auth
    • db
    • realtime

ローカル環境の構築手順

supabase

  1. supabaseでアカウント及びプロジェクト作成

  2. SQL Editorより以下を実行し、taskテーブルを作成する
    (todoアプリ用のため、いらない人はスキップ)

    create table if not exists public.tasks (
      id uuid not null primary key default uuid_generate_v4(),
      user_id uuid not null references auth.users(id) default auth.uid(),
      content text not null,
      is_done boolean not null default false,
      created_at timestamp with time zone default timezone('utc' :: text, now()) not null
    );
    
  3. プロジェクトの設定 > APIから、Project URL及びProject Project API Keys内のanon keyをコピーしておく。

Vite + Svelte + Typescript

前提

nodejsが入った環境を準備

構築手順

$ npm init vite@latest
  # svelte ⇒ typescriptと選択
$ cd <プロジェクト名>
$ npm install
$ npm install @supabase/supabase-js

vite.config.tsを修正

//vite.config.ts

export default defineConfig({
  plugins: [svelte()],
  server: {       // 追加
    host: true,   // 追加
    port: 8080    // 追加
  }               // 追加
})

ここまででhttp://localhost:8080を開くとvite + svelteのwelcome画面が出ているはず。

次に.envファイルをルートディレクトリに作成しanon keyとapi keyを設定する。

.env
VITE_SUPABASE_URL=*****
VITE_SUPABASE_ANON_KEY=******

src/supabaseClient.tsを作成し、呼び出しやすくする

// src/supabaseClient.ts

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY

const realtime_opt = {
  realtime: {
    params: {
      eventsPerSecond: 10,
    }
  }
}

export const supabase = createClient(supabaseUrl, supabaseAnonKey, realtime_opt)

これでsupabaseをフロントで使う準備ができた。
あとは自由にコーディングを進めることができる。
次回はsupabase上のdbの操作について書きます。

例)
image.png

// email+passwordのサインインの場合

<script lang="ts">
  import { supabase } from '../supabaseClient';
  let email = '';
  let password = '';

  const LoginHander = async () => {
    const { data, error } = await supabase.auth.signInWithPassword({
      email: email,
      password: password,
    });
  }
</script>

<form on:submit|preventDefault="{LoginHander}">
  // 省略
</form>

supabase、とってもいい感じ

追記

投稿しました。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?