# 사용자 18만 2천 명을 Supabase로 옮긴 방법

By Tarik Pinarci (https://tarikpinarci.com). Published 2025-03-30. Canonical: https://tarikpinarci.com/ko/blog/migration-to-supabase

몇 달 동안 미루다가 결국 사용자 18만 2천 명을 옮기기까지. 제가 마침내 앱을 Supabase로 옮긴 이야기입니다.

사용자 182,000명을 새 백엔드로 옮기는 건 결코 작은 일이 아닙니다. 풀타임 직장을 다니면서 혼자 모바일 개발을 하는 사람이라면 더욱 그렇습니다. 그래도 해냈습니다. 제 앱 OSM Tactics를 얽히고설킨 NestJS + MongoDB 구성에서, 요즘 백엔드 쪽에서 가장 뜨거운 주제인 Supabase로 옮겼습니다. 이 글에서는 그 여정을 소개합니다. 왜 Supabase를 골랐는지, 어떤 어려움을 겪었는지, 그리고 마이그레이션을 어떻게 해냈는지요.

### 왜 Supabase인가?

앱의 백엔드가 낡았다고 느끼기 시작했을 때 더 나은 걸 찾아 둘러보다가 Supabase가 눈에 들어왔습니다. Firebase와 비슷하지만 시작하기는 더 간단한 오픈 소스 도구입니다. 쉬운 API가 붙은 PostgreSQL 데이터베이스, 실시간 기능, 로그인 기능이 전부 준비되어 있습니다. 모바일 앱을 만드는 저 같은 사람에게는 완벽합니다. 복잡한 서버 잡일에 손대고 싶지 않거든요. Supabase 프로젝트는 5분 정도면 띄울 수 있고, 문서도 아주 명확해서 백엔드 전문가가 아닌 저도 길을 잃지 않았습니다.

그런데 Supabase는 쉽기만 한 게 아니라 점점 커지고 있습니다. 아직 Firebase만큼 거대하지는 않지만 수많은 개발자가 쓰고 있고 커뮤니티도 빠르게 성장하고 있습니다. 제게 필요한 건 다 있습니다. 데이터를 저장할 데이터베이스, 로그인 도구, 파일 업로드 공간, 그리고 서버 전체 없이도 돌릴 수 있는 작은 함수까지요. Firebase는 내부 동작을 감추지만, Supabase는 많은 사람이 신뢰하는 오래되고 믿을 만한 데이터베이스인 PostgreSQL을 씁니다. 그래서 원하는 대로 바꾸고 나중에 막히지 않고 키울 수 있습니다. 게다가 GitHub 같은 곳에서 팁과 요령, 해결책을 나누는 개발자 커뮤니티가 큽니다. 막히면 구글에 검색하거나 누군가에게 물어보면 된다는 걸 알았습니다. 시간이 부족한 혼자 개발하는 저 같은 사람에게 Supabase는 올바른 선택처럼 느껴졌습니다. 단순하지만 제 앱을 감당할 만큼 튼튼합니다.

### 대전환 전의 기존 구성

![](https://cdn-images-1.medium.com/max/2000/0*8Dz9gnNI7LqoicSk.gif)

Supabase로 넘어가기 전에 제가 무엇을 쓰고 있었는지 이야기해 보겠습니다. 제 앱 [OSM Tactics](https://apps.apple.com/us/app/osm-tactics/id1632773385)는 사람들이 전술 전략을 짜는 Android와 iOS용 모바일 게임 앱입니다. 이런 데 관심 있다면 꽤 재미있습니다. 백엔드는 제가 직접 NestJS로 만들었습니다. NestJS는 Node.js용 프레임워크인데, TypeScript와 잘 맞고 코드를 정돈해 줘서 좋아했습니다. 백엔드는 MongoDB와 통신했고, 사용자 정보, 게임 데이터 등을 모두 거기에 저장했습니다. 이 구성을 거의 4년 동안 운영해 왔습니다.

![마이그레이션 전 MongoDB의 마지막 스냅샷, Osm Tactics(다른 이름 "Osm Guide")](https://cdn-images-1.medium.com/max/4072/1*oPXY2-yvVmlns_ufWV4ZGg.png)_마이그레이션 전 MongoDB의 마지막 스냅샷, Osm Tactics(다른 이름 "Osm Guide")_

그런데 문제가 있었습니다. 저는 풀타임 직장이 있는 혼자일 뿐인데, 이 백엔드를 살려 두는 일이 저를 갉아먹고 있었습니다. 처음에는 NestJS와 MongoDB가 괜찮았고, 감당할 수 있었습니다. 하지만 사용자가 늘수록 엉망이 되었습니다. 서버가 죽지 않게 하고, 보안 구멍을 메우고, 충분히 빠르게 유지하는 데 너무 많은 시간을 써야 했습니다. 보안이 최악이었습니다. Node.js를 조금 알긴 하지만 저는 모바일 앱 개발자지 백엔드 전문가가 아닙니다. 그럭저럭 돌아가긴 했지만 자꾸 고장 나는 낡은 차 같았습니다. 영원히 땜질만 할 수는 없었습니다. 머리를 쥐어뜯고 싶게 만들지 않는 새로운 무언가가 필요했습니다.

### 도약: 마이그레이션을 결심하다

![](https://cdn-images-1.medium.com/max/2000/1*CUFLlvoA2ItnVtEFWJulrg.png)

전부 옮기기로 결심하는 데는 시간이 오래 걸렸습니다. 계속 미뤘기 때문입니다. OSM Tactics는 기능이 엄청나게 많은 거대한 앱은 아니지만, 사용자 18만 2천 명은 다루기에 많은 데이터입니다. 데이터가 느슨하고 자유로운 MongoDB에서 모든 게 깔끔한 테이블에 들어가는 Supabase의 PostgreSQL로 옮기는 건 어려워 보였습니다. 데이터 구조를 다시 짜야 했고 중요한 걸 하나도 잃지 않도록 해야 했습니다. 기존 NestJS와 MongoDB 조합은 여전히 돌아가고 있었지만, 곧 터질 것 같은 불길한 느낌이 들었습니다. 그 걱정이 계속 저를 괴롭혔고, 결국 "좋아, 해 보자"라고 말했습니다.

결심하고 나니 제대로 계획을 세워야 했습니다. 자리에 앉아 MongoDB의 데이터를 Supabase 테이블로 어떻게 바꿀지 정리했습니다. 모든 것이 어디로 갈지 지도를 그리는 것과 같았습니다. 첫 단계는 MongoDB에서 모든 데이터를 안전하게 꺼내는 것이었고, 그래서 JSON 파일로 덤프하는 작은 스크립트를 작성했습니다. 코드는 이렇습니다. 기본적이지만 제 몫을 했습니다.

```javascript
async function exportCollection(collectionName, outputFileName, query = {}) {
  try {
    await mongoose.connect(mongoURI);

    const Model = mongoose.model(
      collectionName,
      genericSchema,
      collectionName.toLowerCase()
    );

    const documents = await Model.find(query).lean();

    const outputPath = path.join(__dirname, outputFileName);
    fs.writeFileSync(outputPath, JSON.stringify(documents, null, 2));

    await mongoose.disconnect();

    return documents;
  } catch (error) {
    if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
    }
  }
}
```

이 스크립트는 MongoDB에 연결해 모든 데이터를 꺼내 제 컴퓨터에 JSON 파일로 저장했습니다. 일종의 백업이었습니다. 실수하더라도 모든 걸 잃지 않고 이것저것 시도해 볼 수 있었습니다. 컬렉션마다 실행하고, 파일이 제대로 보이는지 확인하고 나니 사본이 있다는 생각에 조금 마음이 놓였습니다. 그래도 진짜 작업을 시작하는 건 미적거렸습니다. 화면을 멍하니 보며 커피를 홀짝이다가 "내일 하지 뭐"라고 생각하곤 했습니다. 게으름을 멈추고 실제로 뛰어들기까지 큰 결심이 필요했지만, 일단 시작하고 나서는 완전히 몰두했습니다.

### 사용자 마이그레이션: 비밀번호라는 퍼즐

여기서부터 정말 까다로워졌습니다. 사용자 18만 2천 명을 옮기면서 비밀번호가 계속 동작하게 해야 했습니다. 사용자는 앱을 업데이트한 뒤에도 같은 이메일과 비밀번호로 로그인할 수 있기를 기대합니다. 당연히 그래야 합니다. 하지만 그걸 해내는 건 악몽이었습니다. 다행인 점은? [Supabase는 MongoDB 쪽과 마찬가지로 비밀번호에 bcrypt를 씁니다](https://supabase.com/docs/guides/auth/password-security#how-are-passwords-stored). 그래서 비밀번호를 전부 다시 만들거나 사용자에게 새 비밀번호를 고르게 할 필요가 없었습니다. 그랬다면 끔찍한 경험이었을 겁니다. 사람들은 비밀번호 재설정을 싫어하고, 저는 사용자를 꽤 많이 잃었을 겁니다.

### 까다로운 Supabase 인증 테이블 다루기

Supabase에는 로그인을 위한 auth.users 테이블이 있는데, 아주 엄격합니다. 딱 맞게 채워야 하는 필드가 잔뜩 있고, 그렇지 않으면 난리가 납니다. 예를 들어 null 대신 빈 문자열을 넣으면 깨집니다. [이 GitHub 스레드](https://github.com/supabase/auth/issues/1940)에서 다른 사람들이 겪은 에러를 보고 정신이 번쩍 들었습니다. 완벽하게 맞춰야 했습니다. Supabase용 사용자는 이런 모습이었습니다(저는 전화번호 관련 기능을 쓰지 않아서 null입니다. 쓴다면 바꾸세요).

```javascript
const supabaseUser = {
  id: uid,
  email: user.email,
  encrypted_password: user.password || null,
  instance_id: "00000000–0000–0000–0000–000000000000",
  aud: "authenticated",
  role: "authenticated",
  email_confirmed_at: user.createdAt
    ? new Date(user.createdAt).toISOString()
    : new Date().toISOString(),
  created_at: user.createdAt
    ? new Date(user.createdAt).toISOString()
    : new Date().toISOString(),
  updated_at: user.updatedAt ? new Date(user.updatedAt).toISOString() : null,
  last_sign_in_at: null,
  phone: user.phone || null,
  phone_confirmed_at: null,
  confirmed_at: user.createdAt
    ? new Date(user.createdAt).toISOString()
    : new Date().toISOString(),
  invited_at: null,
  confirmation_token: "",
  confirmation_sent_at: null,
  recovery_token: "",
  recovery_sent_at: null,
  email_change_token_new: "",
  email_change: "",
  email_change_sent_at: null,
  email_change_token_current: "",
  email_change_confirm_status: 0,
  banned_until: null,
  reauthentication_token: "",
  reauthentication_sent_at: null,
  is_super_admin: null,
  phone_change: "",
  phone_change_token: "",
  phone_change_sent_at: null,
  is_sso_user: false,
  deleted_at: null,
  is_anonymous: false,
  raw_user_meta_data: JSON.stringify(rawUserMetaData),
  raw_app_meta_data: JSON.stringify(rawAppMetaData),
};
```

필드를 하나하나 전부 맞춰야 Supabase가 받아 줬습니다. MongoDB 사용자를 전부 옮기기 위해, 사용자를 가져와 이 형식으로 바꾸고 CSV 파일로 저장하는 더 큰 스크립트를 작성했습니다. 그 스크립트는 이렇습니다. 길지만 전체 과정을 보여 줍니다.

```javascript
const fs = require("fs");
const path = require("path");
const { parse } = require("json2csv");
const { v4: uuidv4 } = require("uuid");
const mongoose = require("mongoose");
const mongoURI = "your-connection-string";

// Define a generic schema for flexible document structure
const userSchema = new mongoose.Schema({}, { strict: false });
async function fetchUsersFromMongoDB() {
  try {
    console.log("Connecting to MongoDB…");
    await mongoose.connect(mongoURI);
    console.log("Connected to MongoDB");
    const UserModel = mongoose.model("Users", userSchema, "users");
    console.log("Fetching users from MongoDB…");
    const users = await UserModel.find({}).lean();
    console.log(`Found ${users.length} users in MongoDB`);
    await mongoose.disconnect();
    console.log("Disconnected from MongoDB");
    return users;
  } catch (error) {
    console.error("Error fetching users from MongoDB:", error);
    if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
    }
    throw error;
  }
}

async function processUsers() {
  console.time("Total processing time");
  const mongoUsersFilePath = path.join(__dirname, "mongo_users.json");
  try {
    // Step 1: Fetch users from MongoDB
    const users = await fetchUsersFromMongoDB();
    // Step 2: Write users to a fresh JSON file
    fs.writeFileSync(mongoUsersFilePath, JSON.stringify(users, null, 2));
    console.log(`Fresh users data written to: ${mongoUsersFilePath}`);
    // Step 3: Read the fresh users file
    const usersData = JSON.parse(fs.readFileSync(mongoUsersFilePath, "utf8"));
    console.log(`Read ${usersData.length} users from fresh file`);
    // Step 4: Filter users to include only those with an email or at least one provider
    const filteredUsers = usersData.filter((user) => {
      return user.email || user.googleId || user.appleId;
    });
    console.log(`Filtered users: ${filteredUsers.length}`);
    // Create a Set to track used IDs and ensure uniqueness
    const usedIds = new Set();
    const usedEmails = new Set();
    const duplicateEmails = [];
    // Step 5: Transform the data to match Supabase Auth users structure
    const transformedUsers = [];
    filteredUsers.forEach((user) => {
      if (!user.email) {
        console.log("Skipping user without email:", user._id);
        return;
      }
      // Check for duplicate email
      const lowerEmail = user.email.toLowerCase();
      if (usedEmails.has(lowerEmail)) {
        duplicateEmails.push({
          email: user.email,
          id: user._id,
          googleId: user.googleId,
          appleId: user.appleId,
        });
        console.warn(`Duplicate email detected and skipped: ${user.email}`);
        return;
      }
      // Mark this email as used
      usedEmails.add(lowerEmail);
      let uid = uuidv4();
      while (usedIds.has(uid)) {
        console.warn("Duplicate ID detected:", uid);
        uid = uuidv4();
      }
      usedIds.add(uid);
      const rawUserMetaData = {
        sub: uid,
        email: user.email,
        email_verified: true,
        phone_verified: false,
      };
      const providers = [];
      // Check for Google ID
      if (user.googleId) {
        providers.push("google");
        rawUserMetaData.iss = "https://accounts.google.com";
        rawUserMetaData.sub = user.googleId;
        rawUserMetaData.provider_id = user.googleId;
      }
      // Check for Apple ID
      if (user.appleId) {
        providers.push("apple"); // Only override iss and sub if Google wasn't already set
        if (!user.googleId) {
          rawUserMetaData.iss = "https://appleid.apple.com";
          rawUserMetaData.sub = user.appleId;
          rawUserMetaData.provider_id = user.appleId;
        }
      }
      // If no external providers, use email
      if (providers.length === 0) {
        providers.push("email");
      }
      // Set the raw app metadata
      const rawAppMetaData = {
        provider: providers[0], // Primary provider is the first one
        providers: providers, // All providers in an array
      };
      transformedUsers.push({
        id: uid,
        email: user.email || null,
        encrypted_password: user.password,
        instance_id: "00000000–0000–0000–0000–000000000000",
        aud: "authenticated",
        role: "authenticated",
        invited_at: null,
        confirmation_token: "",
        confirmation_sent_at: null,
        recovery_token: "",
        recovery_sent_at: null,
        email_change_token_new: "",
        email_change: "",
        email_change_sent_at: null,
        last_sign_in_at: new Date().toISOString(),
        is_super_admin: null,
        phone: "",
        phone_confirmed_at: null,
        phone_change: "",
        phone_change_token: "",
        phone_change_sent_at: null,
        confirmed_at: new Date().toISOString(),
        email_change_token_current: "",
        email_change_confirm_status: 0,
        banned_until: null,
        reauthentication_token: "",
        reauthentication_sent_at: null,
        is_sso_user: false,
        deleted_at: null,
        is_anonymous: false,
        created_at: user.createdAt
          ? new Date(user.createdAt).toISOString()
          : new Date().toISOString(),
        updated_at: null,
        email_confirmed_at: user.createdAt
          ? new Date(user.createdAt).toISOString()
          : new Date().toISOString(),
        phone: user.phone || null,
        phone_confirmed_at: null,
        raw_user_meta_data: rawUserMetaData,
        raw_app_meta_data: rawAppMetaData,
      });
    });
    // Step 6: Convert the transformed data to CSV
    const csvFields = [
      "id",
      "email",
      "encrypted_password",
      "instance_id",
      "aud",
      "role",
      "email_confirmed_at",
      "invited_at",
      "confirmation_token",
      "confirmation_sent_at",
      "recovery_token",
      "recovery_sent_at",
      "email_change_token_new",
      "email_change",
      "email_change_sent_at",
      "last_sign_in_at",
      "raw_app_meta_data",
      "raw_user_meta_data",
      "is_super_admin",
      "created_at",
      "updated_at",
      "phone",
      "phone_confirmed_at",
      "phone_change",
      "phone_change_token",
      "phone_change_sent_at",
      "confirmed_at",
      "email_change_token_current",
      "email_change_confirm_status",
      "banned_until",
      "reauthentication_token",
      "reauthentication_sent_at",
      "is_sso_user",
      "deleted_at",
      "is_anonymous",
    ];
    // Write duplicate emails to a file for reference
    if (duplicateEmails.length > 0) {
      fs.writeFileSync(
        path.join(__dirname, "duplicate_emails.json"),
        JSON.stringify(duplicateEmails, null, 2)
      );
      console.log("Duplicate emails written to duplicate_emails.json");
    }
    const csv = parse(transformedUsers, { fields: csvFields });
    // Step 7: Write the CSV to a file
    const csvFilePath = path.join(__dirname, "supabase_users.csv");
    fs.writeFileSync(csvFilePath, csv);
    console.log("CSV file has been generated:", csvFilePath);
    // Step 8: Delete the temporary fresh users file
    if (fs.existsSync(mongoUsersFilePath)) {
      fs.unlinkSync(mongoUsersFilePath);
      console.log(`Temporary file deleted: ${mongoUsersFilePath}`);
    }
    console.timeEnd("Total processing time");
  } catch (error) {
    console.error("Error processing users:", error);
  } finally {
    if (fs.existsSync(mongoUsersFilePath)) {
      try {
        fs.unlinkSync(mongoUsersFilePath);
        console.log(`Temporary file deleted: ${mongoUsersFilePath}`);
      } catch (deleteError) {
        console.error(`Error deleting temporary file: ${deleteError.message}`);
      }
    }
  }
}
```

CSV를 만든 뒤 Supabase에 auth.users와 똑같이 생긴 임시 테이블을 만들었습니다. 실제 테이블의 구조는 긴 SQL로, Supabase 에디터의 schema auth > users > Definition에서 볼 수 있습니다.

```sql
    create table auth.users (
      instance_id uuid null,
      id uuid not null,
      aud character varying(255) null,
      role character varying(255) null,
      email character varying(255) null,
      encrypted_password character varying(255) null,
      email_confirmed_at timestamp with time zone null,
      invited_at timestamp with time zone null,
      confirmation_token character varying(255) null,
      confirmation_sent_at timestamp with time zone null,
      recovery_token character varying(255) null,
      recovery_sent_at timestamp with time zone null,
      email_change_token_new character varying(255) null,
      email_change character varying(255) null,
      email_change_sent_at timestamp with time zone null,
      last_sign_in_at timestamp with time zone null,
      raw_app_meta_data jsonb null,
      raw_user_meta_data jsonb null,
      is_super_admin boolean null,
      created_at timestamp with time zone null,
      updated_at timestamp with time zone null,
      phone text null default null::character varying,
      phone_confirmed_at timestamp with time zone null,
      phone_change text null default ''::character varying,
      phone_change_token character varying(255) null default ''::character varying,
      phone_change_sent_at timestamp with time zone null,
      confirmed_at timestamp with time zone GENERATED ALWAYS as (LEAST(email_confirmed_at, phone_confirmed_at)) STORED null,
      email_change_token_current character varying(255) null default ''::character varying,
      email_change_confirm_status smallint null default 0,
      banned_until timestamp with time zone null,
      reauthentication_token character varying(255) null default ''::character varying,
      reauthentication_sent_at timestamp with time zone null,
      is_sso_user boolean not null default false,
      deleted_at timestamp with time zone null,
      is_anonymous boolean not null default false,
      constraint users_pkey primary key (id),
      constraint unique_email unique (email),
      constraint users_phone_key unique (phone),
      constraint users_email_change_confirm_status_check check (
        (
          (email_change_confirm_status >= 0)
          and (email_change_confirm_status <= 2)
        )
      )
    ) TABLESPACE pg_default;

    create unique INDEX IF not exists confirmation_token_idx on auth.users using btree (confirmation_token) TABLESPACE pg_default
    where
      ((confirmation_token)::text !~ '^[0-9 ]*$'::text);

    create unique INDEX IF not exists email_change_token_current_idx on auth.users using btree (email_change_token_current) TABLESPACE pg_default
    where
      (
        (email_change_token_current)::text !~ '^[0-9 ]*$'::text
      );

    create unique INDEX IF not exists email_change_token_new_idx on auth.users using btree (email_change_token_new) TABLESPACE pg_default
    where
      (
        (email_change_token_new)::text !~ '^[0-9 ]*$'::text
      );

    create unique INDEX IF not exists reauthentication_token_idx on auth.users using btree (reauthentication_token) TABLESPACE pg_default
    where
      (
        (reauthentication_token)::text !~ '^[0-9 ]*$'::text
      );

    create unique INDEX IF not exists recovery_token_idx on auth.users using btree (recovery_token) TABLESPACE pg_default
    where
      ((recovery_token)::text !~ '^[0-9 ]*$'::text);

    create unique INDEX IF not exists users_email_partial_key on auth.users using btree (email) TABLESPACE pg_default
    where
      (is_sso_user = false);

    create index IF not exists users_instance_id_email_idx on auth.users using btree (instance_id, lower((email)::text)) TABLESPACE pg_default;

    create index IF not exists users_instance_id_idx on auth.users using btree (instance_id) TABLESPACE pg_default;

    create index IF not exists users_is_anonymous_idx on auth.users using btree (is_anonymous) TABLESPACE pg_default;
```

이 구조를 임시 테이블에 그대로 복사하고, CSV를 업로드한 다음, 이 스크립트로 사용자를 실제 auth.users 테이블로 천 명씩 옮겼습니다.

```sql
    DO $$
    DECLARE
        batch_size INT := 1000;  -- Adjust batch size as needed
        records_inserted INT;
    BEGIN
        LOOP
            INSERT INTO auth.users (
                id,
                email,
                encrypted_password,
                instance_id,
                aud,
                role,
                email_confirmed_at,
                invited_at,
                confirmation_token,
                confirmation_sent_at,
                recovery_token,
                recovery_sent_at,
                email_change_token_new,
                email_change,
                email_change_sent_at,
                last_sign_in_at,
                raw_app_meta_data,
                raw_user_meta_data,
                is_super_admin,
                created_at,
                updated_at,
                phone,
                phone_confirmed_at,
                phone_change,
                phone_change_token,
                phone_change_sent_at,
                email_change_token_current,
                email_change_confirm_status,
                banned_until,
                reauthentication_token,
                reauthentication_sent_at,
                is_sso_user,
                deleted_at,
                is_anonymous
            )
            SELECT
                id,
                email,
                encrypted_password,
                COALESCE(instance_id, '00000000-0000-0000-0000-000000000000'),
                COALESCE(aud, 'authenticated'),
                COALESCE(NULLIF(role, ''), 'authenticated'),
                COALESCE(email_confirmed_at, NOW()),
                COALESCE(invited_at, NULL),
                COALESCE(confirmation_token, ''),
                COALESCE(confirmation_sent_at, NULL),
                COALESCE(recovery_token, ''),
                COALESCE(recovery_sent_at, NULL),
                COALESCE(email_change_token_new, ''),
                COALESCE(email_change, ''),
                COALESCE(email_change_sent_at, NULL),
                COALESCE(last_sign_in_at, NOW()),
                raw_app_meta_data,  -- Use value from test_users table
                raw_user_meta_data, -- Use value from test_users table
                COALESCE(is_super_admin, NULL),
                COALESCE(created_at, NOW()),
                COALESCE(updated_at, NOW()),
                COALESCE(phone, NULL),
                COALESCE(phone_confirmed_at, NULL),
                COALESCE(phone_change, ''),
                COALESCE(phone_change_token, ''),
                COALESCE(phone_change_sent_at, NULL),
                COALESCE(email_change_token_current, ''),
                COALESCE(email_change_confirm_status, 0),
                COALESCE(banned_until, NULL),
                COALESCE(reauthentication_token, ''),
                COALESCE(reauthentication_sent_at, NULL),
                COALESCE(is_sso_user, false),
                COALESCE(deleted_at, NULL),
                COALESCE(is_anonymous, false)
            FROM public.test_users
            LIMIT batch_size
            ON CONFLICT (email) DO NOTHING;  -- Ignore duplicates

            GET DIAGNOSTICS records_inserted = ROW_COUNT;

            -- Exit the loop if no more records are inserted
            IF records_inserted = 0 THEN
                EXIT;
            END IF;
        END LOOP;
    END $$;
```

이렇게 하면 내보내기, 변환, 불러오기의 모든 단계를 볼 수 있었습니다. 멋진 도구를 쓰는 것보다 시간은 더 걸렸겠지만, 무슨 일이 일어나는지 정확히 아는 게 좋았습니다. CSV를 불러온 뒤 임시 테이블을 확인하고, 몇몇 행을 샘플로 점검한 다음, 배치 스크립트가 막히지 않고 도는지 지켜봤습니다.

### 커스텀 필드를 넣을 자리가 없다

Supabase의 auth.users 테이블에는 직접 필드를 추가할 수 없어서 당황했습니다. MongoDB에서는 username 필드를 그냥 넣으면 끝이었습니다. 하지만 Supabase는 안 된다고 합니다. 주어진 것만 써야 합니다. 일종의 JSON 주머니인 raw_user_meta_data에 추가 데이터를 밀어 넣을까도 생각했지만, 나중에 검색하기에 지저분합니다. 대신 사용자 ID로 auth.users와 연결되는 새 profiles 테이블을 만들었습니다. username과 locale 같은 것들을 여기에 담아 모든 걸 깔끔하게 유지합니다.

도움이 될 만한 이 토론도 참고하세요: [https://github.com/orgs/supabase/discussions/3491](https://github.com/orgs/supabase/discussions/3491)

이걸 구성하느라 일이 더 늘었습니다. MongoDB에서 추가 필드를 꺼내고, 올바른 사용자와 매칭하고, 새 테이블에 불러와야 했습니다. 그 데이터를 가져오는 스크립트를 하나 더 작성해 CSV로 바꾸고, 인증 작업이 끝난 뒤 Supabase에 업로드했습니다. 이제는 나중에 아무것도 깨뜨리지 않고 필드를 추가할 수 있어서 더 나은 구성이지만, 테이블 하나가 아니라 두 개를 다뤄야 해서 마이그레이션이 더 오래 걸렸습니다.

### Google/Apple 로그인 마이그레이션

![](https://cdn-images-1.medium.com/max/2400/0*ojwVN2SEuLBx9Ybn.jpeg)

Google과 Apple 로그인도 골치 아팠습니다. MongoDB에는 googleId와 appleId 필드가 있었고, 어떤 사용자는 이메일 하나에 둘 다 연결되어 있었습니다. Supabase는 이를 raw_user_meta_data 안의 iss, sub, provider_id 같은 특수 필드로 처리합니다.

제가 구성한 방법은 이렇습니다.

```javascript
const uid = uuidv4();
const providers = [];
// Build raw user metadata
const rawUserMetaData = {
  sub: uid,
  email: user.email,
  email_verified: true,
  phone_verified: false,
};
// Check for Google ID
if (user.googleId) {
  providers.push("google");
  rawUserMetaData.iss = "https://accounts.google.com";
  rawUserMetaData.sub = user.googleId;
  rawUserMetaData.provider_id = user.googleId;
}
// Check for Apple ID
if (user.appleId) {
  providers.push("apple");
  if (!user.googleId) {
    rawUserMetaData.iss = "https://appleid.apple.com";
    rawUserMetaData.sub = user.appleId;
    rawUserMetaData.provider_id = user.appleId;
  }
}
// If no external providers, use email
if (providers.length === 0) {
  providers.push("email");
}
```

앱에서는 로그인 흐름이 Supabase API를 쓰도록 업데이트했습니다. Apple은 이렇게 했습니다.

```javascript
import * as AppleAuthentication from "expo-apple-authentication";
import { supabase } from "your-supabase-client";

const credential = await AppleAuthentication.signInAsync({
  requestedScopes: [
    AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
    AppleAuthentication.AppleAuthenticationScope.EMAIL,
  ],
});
if (credential.identityToken) {
  const { data, error } = await supabase.auth.signInWithIdToken({
    provider: "apple",
    token: credential.identityToken,
  });
}
```

Google은 이렇게 했습니다.

```javascript
import { GoogleSignin } from "@react-native-google-signin/google-signin";
import { supabase } from "your-supabase-client";

const googleUser = await GoogleSignin.signIn();

if (googleUser.idToken) {
  const { data, error } = await supabase.auth.signInWithIdToken({
    provider: "google",
    token: googleUser.idToken,
  });
}
```

동작은 했지만, Google과 Apple을 모두 쓰는 사용자를 처리하는 게 까다로웠습니다. 하나를 메인 ID로 정하고 다른 하나를 추가로 등록해야 했습니다. 아무도 로그인하지 못하는 일이 없도록 앱에서 여러 번 테스트했습니다.

> **주의: Supabase의 CSV 내보내기 문제 가능성**
> 오늘(2025년 3월 29일) 기준으로 테이블 데이터를 CSV로 내보내는 기능은 [믿을 수 없을](https://github.com/supabase/supabase/issues/27102) 수 있습니다. Supabase와 원본 소스의 데이터를 비교할 때 이 점을 염두에 두세요.

### TypeScript 타입 생성하기

Supabase에는 TypeScript 타입을 대신 만들어 주는 멋진 기능이 있습니다. [명령어 하나만 실행하면](https://supabase.com/docs/guides/api/rest/generating-types#generating-types-using-supabase-cli) 데이터베이스가 정확히 어떻게 생겼는지 코드에 알려 주는 파일을 만들어 줍니다. React Native와 Expo로 만든 제 앱에는 엄청난 일이었습니다. 어떤 데이터를 받을지 추측하거나 타입을 직접 작성할 필요가 없었습니다. 실수하면 TypeScript가 소리를 질러 줘서 버그가 크게 줄었습니다. 전에는 어이없는 실수를 고치느라 몇 시간을 썼는데, 이제는 훨씬 빠릅니다.

테이블을 구성한 뒤 명령어를 실행해 타입 파일을 받고 앱에 연결했습니다. 그러자 user.email이나 profile.username 같은 것들이 그냥 동작했습니다. 철자를 맞게 썼는지 더 이상 고민할 필요가 없었습니다. 작은 일이지만, 앱 코딩이 추측 게임이 아니라 이기는 게임처럼 느껴지게 해 줬습니다.

### 데이터베이스 함수에 일 맡기기

Supabase에서는 데이터베이스 안에서 실행되는 작은 SQL 함수를 작성할 수 있는데, 아주 편리합니다. 데이터를 바꾸려고 앱 쪽 코드를 잔뜩 쓰는 대신 데이터베이스가 처리하게 했습니다.

사용자 프로필에 크레딧을 추가하려고 만든 함수는 이렇습니다.

```sql
    declare
      current_credits int;
      new_credits int;
    begin
      -- Get current credits from user_profiles table
      select assistant_credits
      into current_credits
      from public.user_profiles
      where public.user_profiles.user_id = increase_assistant_credits.user_id;

      if current_credits is null then
        current_credits := 0;
      end if;

      new_credits := current_credits + credits_to_add;

      -- Update assistant_credits in user_profiles table
      update public.user_profiles
      set assistant_credits = new_credits
      where public.user_profiles.user_id = increase_assistant_credits.user_id;

      return new_credits;
    end;
```

이 함수는 사용자의 크레딧을 가져와 더하고, 다시 저장하는 일을 한 번에 합니다. 이게 없다면 크레딧을 가져오고, 앱에서 더하고, 다시 보내야 하니 코드도 늘고 실수할 여지도 늘어납니다. 다른 작업을 위해서도 이런 함수를 몇 개 작성했고, 데이터베이스가 무거운 일을 맡아 주니 앱이 더 빠릿하게 느껴졌습니다.

### 백엔드에 관한 주의 사항

반전이 하나 있습니다. Supabase가 제 백엔드를 완전히 없애 주지는 않았습니다. 일부 관리자용 로그인 기능을 쓰려면 [service_role 키](https://supabase.com/docs/guides/api/api-keys#the-servicerole-key)가 필요한데, 이 키는 앱에 넣으면 안전하지 않습니다. 그래서 그런 비밀 작업을 처리하는 작은 NestJS 서버를 남겨 두었습니다. 예전만큼 크지는 않지만, 보안을 지키기 위해 있습니다. 대부분의 일은 Supabase가 하므로 예전 구성보다 여전히 훨씬 쉽습니다.

### 마치며: 고생할 만한 가치가 있었다

![](https://cdn-images-1.medium.com/max/2000/0*rugop3f6Ns9U4Ayl.jpg)

사용자 182,000명을 Supabase로 옮기는 건 기술적인 도전이었을 뿐 아니라 정신적인 도전이기도 했습니다. 미루기, 늦은 밤, 그리고 수없이 되묻는 의심 속에서 정말로 모든 걸 망가뜨릴 수도 있겠다고 생각한 순간들이 있었습니다. 스트레스와 망설임으로 가득한 느린 강행군이었습니다. 하지만 깨지기 쉬운 NestJS + MongoDB 구성을 떠나 더 깔끔하고 유지보수하기 좋은 곳으로 옮긴 건 확실히 그럴 만한 가치가 있었습니다.

Supabase는 풀타임 직장을 다니며 혼자 개발하는 제게 필요했던 단순함, 유연함, 커뮤니티의 지원을 주었습니다. 여러분도 앱의 백엔드 마이그레이션을 고민하고 있다면, 충분히 해낼 수 있다는 걸 알아 두세요. 빠르지도, 고통 없지도 않을 겁니다. 하지만 약간의 계획(그리고 아마 긴 밤 몇 번)만 있다면, 반대편에 도착했을 때 정말로 믿을 수 있는 구성을 갖게 될 겁니다.

