1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js×Supabase】SSRでSupabaseにデータをInsertする手順

Posted at

はじめに

先日下記の記事にて、「Supabaseの環境変数の冒頭にNEXT_PUBLIC_を付ける必要がある。」と記述をしました。

NEXT_PUBLIC_をつけるとクライアント側での参照が可能になる反面、情報漏洩・悪用といったセキュリティ上のリスクもあります。

そこで今回は、NEXT_PUBLIC_を使用せずにサーバー側でのみ使用していきます。
今回はデータ挿入(Insert)の処理を例に説明していきます。

Supabaseのインストール&初期設定は完了している前提とします。

1.Supabaseの設定ファイル作成

src/utils/supabase.tsを作成します。

Supabaseクライアントの設定を外部で管理することで、他のAPI Routeやサーバーサイドロジックでも再利用できます。

supabaseUrlsupabaseKeyの値は.env.localで管理しています。
.env.localはGit等にあげないように注意

supabase.ts
import { createClient } from "@supabase/supabase-js";

const supabaseUrl = process.env.SUPABASE_URL as string;
const supabaseKey = process.env.SUPABASE_KEY as string;

export const supabase = createClient(supabaseUrl, supabaseKey);

2.APIルート作成

Next.jsでは、pages/api配下にAPIルートのファイルを作成する必要があります。

クライアントからのPOSTリクエストを受け取り、Supabaseにデータを挿入します。
クライアント側の処理は後続の手順で作成します。

supabaseFunctions.ts
import { supabase } from "../../src/utils/supabase";
import type { NextApiRequest, NextApiResponse } from "next";

// API Routeとしてエクスポートされる関数
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "POST") {
    const { value } = req.body;

    // supabaseを使用してデータを挿入
    try {
      const { data, error } = await supabase
        .from("motivation_bodymake")
        .insert([{ value }]);

      if (error) {
        return res.status(500).json({ error: error.message });
      }

      // 挿入したデータを返す
      return res.status(200).json({ data: data ? data[0] : null });
      
    } catch (err) {
      // エラーハンドリング
      return res.status(500).json({ error: "Something went wrong." });
    }
  }
}

3.クライアントサイドのコード作成

fetchを使って、先ほど作成したAPI RouteにPOSTリクエストを送ります。

fetchについての説明は下記を参照してください。
fetchはGETリクエストが規定ですが、今回はPOSTリクエストを行うのでmethodにPOSTを指定します。そして、bodyに送りたいデータを指定します。(今回はvalueというデータを送ります。)

index.tsx
//データ挿入処理
export const addData = async (value: string) => {
  // fetch関数を使用して手順2で作成したAPIエンドポイントにリクエストを送信
  const res = await fetch("/api/supabaseFunctions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ value }),
  });

  const data = await res.json();
  return data;
};

おわりに

一番最初に感じたことは「やること多いな。。難しそうだな」でしたが、しっかりと処理を追っていくとシンプルな流れかと思います。
学習頑張りましょう!

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?