Da mesi di rinvii alla migrazione di 182k utenti: come ho finalmente spostato la mia app su Supabase.
Migrare 182.000 utenti su un nuovo backend non è un'impresa da poco, soprattutto quando sei uno sviluppatore mobile solitario che si destreggia con un lavoro a tempo pieno. Ma ce l'ho fatta. Ho spostato la mia app, OSM Tactics, da un groviglio NestJS + MongoDB a Supabase, l'argomento caldo del momento nel mondo backend. In questo articolo ti racconto il percorso: perché ho scelto Supabase, le difficoltà che ho incontrato e come ho portato a termine la migrazione.
Perché Supabase?
Quando il backend della mia app ha cominciato a sembrare vecchio, mi sono guardato intorno per trovare qualcosa di meglio, e Supabase ha attirato la mia attenzione. È un progetto open source simile a Firebase ma più semplice da cui partire. Ti dà un database PostgreSQL con un'API facile, funzioni in tempo reale e il login già pronto. Per me, uno che costruisce app mobile, è perfetto: non voglio pasticciare con roba complicata lato server. Puoi avere un progetto Supabase funzionante in tipo cinque minuti, e la documentazione è chiarissima, quindi non mi sono sentito perso anche se non sono un esperto di backend.
Supabase però non è solo facile: sta diventando grande. Non è ancora enorme come Firebase, ma tantissimi sviluppatori lo usano e la community cresce in fretta. Ha tutto quello che mi serve: un database per salvare i dati, strumenti per il login, un posto dove caricare file e perfino piccole funzioni che posso eseguire senza un server completo. Firebase nasconde come funziona, mentre Supabase usa PostgreSQL, un database vecchio e affidabile di cui si fidano tantissime persone. Questo significa che posso cambiare le cose come voglio e farle crescere più avanti senza restare bloccato. In più c'è un grande gruppo di sviluppatori online che condivide consigli, trucchi e soluzioni su posti come GitHub. Sapevo che se mi fossi bloccato avrei potuto cercare su Google o chiedere a qualcuno. Per uno che programma da solo e ha poco tempo come me, Supabase sembrava la scelta giusta: semplice ma abbastanza solido da reggere la mia app.
Il vecchio setup prima del grande cambio

Prima di passare a Supabase, parliamo di cosa usavo. La mia app, OSM Tactics, è un gioco mobile per Android e iOS in cui le persone pianificano strategie tattiche: niente male, se ti piace il genere. Il backend l'avevo costruito io con NestJS, un framework per Node.js che mi piaceva perché funziona con TypeScript e tiene le cose in ordine. Comunicava con MongoDB, un database in cui tenevo tutte le informazioni degli utenti, i dati di gioco e altre cose. Usavo questo setup da quasi quattro anni.
_L'ultima istantanea di mongodb prima della migrazione, Osm Tactics alias “Osm Guide” _
Ma ecco il problema: sono una persona sola con un lavoro a tempo pieno, e tenere in vita questo backend mi stava distruggendo. All'inizio NestJS e MongoDB andavano bene, riuscivo a gestirli. Ma con l'arrivo di nuovi utenti la situazione si è complicata. Dovevo passare troppo tempo ad assicurarmi che il server non crashasse, a chiudere falle di sicurezza e a mantenerlo abbastanza veloce. La sicurezza era la parte peggiore: conosco un po' di Node.js, ma sono uno sviluppatore di app mobile, non un esperto di backend. Funzionava ancora, più o meno, ma era come una vecchia auto che continua a guastarsi. Non potevo continuare a rattopparlo per sempre: mi serviva qualcosa di nuovo che non mi facesse venire voglia di strapparmi i capelli.
Il salto: decidere di migrare

Decidere di spostare tutto non è stato veloce: ci è voluta un'eternità perché continuavo a rimandare. OSM Tactics non è un'app gigantesca con tantissime funzioni, ma 182k utenti sono un sacco di dati da gestire. Passare da MongoDB, dove i dati sono sciolti e liberi, al PostgreSQL di Supabase, dove tutto sta in tabelle ordinate, sembrava difficile. Avrei dovuto rifare la struttura dei dati e assicurarmi di non perdere niente di importante. La vecchia combinazione NestJS-MongoDB funzionava ancora, ma avevo la brutta sensazione che sarebbe esplosa presto. Quella preoccupazione ha continuato a tormentarmi finché non ho detto: "Va bene, facciamolo".
Una volta deciso, ho dovuto pianificare tutto per bene. Mi sono seduto e ho capito come trasformare la mia roba di MongoDB in tabelle Supabase, come disegnare una mappa di dove sarebbe andato ogni pezzo. Il primo passo era estrarre tutti i dati da MongoDB in sicurezza, quindi ho scritto un piccolo script per esportarli in file JSON. Ecco il codice: è basilare ma ha fatto il suo lavoro.
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();
}
}
}
Questo script si collegava a MongoDB, estraeva tutti i dati e li salvava come file JSON sul mio computer. Era come un backup: potevo fare esperimenti senza perdere tutto se avessi combinato un guaio. L'ho eseguito per ogni collection, ho controllato i file per vedere se erano a posto e mi sono sentito un po' meglio sapendo di avere delle copie. Eppure continuavo a tirarla per le lunghe prima di iniziare il lavoro vero: fissavo lo schermo, sorseggiavo il caffè e pensavo "Magari domani". Mi ci è voluta una bella spinta per smettere di battere la fiacca e mettermi davvero all'opera, ma una volta partito ci ho messo tutto me stesso.
Migrare gli utenti: il rompicapo delle password
È qui che le cose si sono fatte davvero complicate: spostare 182k utenti mantenendo funzionanti le loro password. Dopo l'aggiornamento dell'app, gli utenti si aspettano di accedere con la stessa email e la stessa password: è così che deve essere. Ma farlo è stato un incubo. La cosa bella? Supabase usa bcrypt per le password, proprio come MongoDB, quindi non ho dovuto rifarle tutte né costringere gli utenti a sceglierne di nuove. Sarebbe stata un'esperienza terribile: la gente odia reimpostare la password, e ne avrei persi parecchi.
Alle prese con la pignola tabella auth di Supabase
Supabase ha una tabella auth.users per i login, ed è severissima. Ha un sacco di campi da compilare esattamente nel modo giusto, altrimenti va in tilt: per esempio, se metti una stringa vuota invece di null, si rompe. Ho trovato alcuni errori in cui erano incappati altri in questo thread su GitHub, e mi sono spaventato a sufficienza. Dovevo rispettarla alla perfezione. Ecco com'era un utente per Supabase (non usavo i dati del telefono, quindi quelli sono null; cambiali se li usi):
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),
};
Dovevo azzeccare ogni singolo campo, altrimenti Supabase non lo accettava. Per spostare tutti i miei utenti MongoDB ho scritto uno script più grande che li prendeva, li trasformava in questo formato e li salvava in un file CSV. Ecco lo script: è lungo ma mostra tutto il processo.
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}`);
}
}
}
}
Una volta ottenuto il CSV, ho creato in Supabase una tabella finta uguale ad auth.users. La struttura della tabella vera è un lungo pezzo di SQL che puoi vedere nell'editor di Supabase sotto schema auth > users > Definition:
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;
Ho copiato quella struttura per la mia tabella temporanea, ci ho caricato il CSV e poi ho usato questo script per spostare gli utenti nella vera tabella auth.users mille alla volta:
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 $$;
In questo modo potevo vedere ogni passaggio: esportazione, trasformazione, caricamento. Ci è voluto più tempo che con qualche strumento sofisticato, ma mi piaceva sapere esattamente cosa stava succedendo. Controllavo la tabella temporanea dopo aver caricato il CSV, verificavo a campione qualche riga e poi guardavo lo script a lotti girare per assicurarmi che non si inceppasse.
Niente spazio per i campi personalizzati
La tabella auth.users di Supabase non ti permette di aggiungere campi tuoi, e questo mi ha spiazzato. In MongoDB avrei semplicemente infilato lì un campo username, niente di che. Ma Supabase dice di no: devi accontentarti di quello che ti dà. Avevo pensato di infilare la roba in più in raw_user_meta_data, che è una specie di sacco JSON, ma poi diventa scomodo per le ricerche. Ho creato invece una nuova tabella profiles collegata ad auth.users tramite l'ID utente. Contiene cose come username e locale, e tiene tutto in ordine.
Vedi anche questa discussione, che potrebbe esserti utile: https://github.com/orgs/supabase/discussions/3491
Configurarla ha significato più lavoro: dovevo estrarre quei campi in più da MongoDB, abbinarli agli utenti giusti e caricarli nella nuova tabella. Ho scritto un altro script per prendere quei dati, li ho trasformati in un CSV e li ho caricati su Supabase dopo aver finito la parte di autenticazione. Ora il setup è migliore perché posso aggiungere altri campi in futuro senza rompere niente, ma la migrazione ha richiesto più tempo, perché le tabelle da gestire erano due invece di una.
Migrare gli accessi con Google/Apple

Anche gli accessi con Google e Apple sono stati una seccatura. In MongoDB avevo i campi googleId e appleId, e alcuni utenti li avevano entrambi legati alla stessa email. Supabase li gestisce con campi speciali in raw_user_meta_data come iss, sub e provider_id.
Ecco come l'ho impostato:
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");
}
Nell'app ho aggiornato i flussi di accesso per usare le API di Supabase. Per Apple:
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,
});
}
E per Google:
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,
});
}
Ha funzionato, ma gestire gli utenti con sia Google sia Apple è stato complicato: dovevo sceglierne uno come ID principale e indicare l'altro come aggiuntivo. L'ho testato un sacco nell'app per essere sicuro che nessuno restasse chiuso fuori.
Attenzione: possibili problemi con l'esportazione CSV in Supabase A oggi (29/03/2025), esportare i dati di una tabella in CSV potrebbe essere poco affidabile. Tienilo presente quando confronti i dati tra Supabase e la tua fonte originale.
Generare i tipi TypeScript
Supabase ha un trucco fantastico: genera i tipi TypeScript al posto tuo. Esegui un solo comando e ti restituisce file che dicono al tuo codice esattamente com'è fatto il tuo database. Per la mia app React Native ed Expo è stata una svolta: non dovevo indovinare quali dati avrei ricevuto né scrivere i tipi a mano. Ha ridotto parecchio i bug, perché TypeScript mi sgridava se sbagliavo qualcosa. Prima passavo ore a correggere errori stupidi; ora è molto più veloce.
Ho eseguito il comando dopo aver configurato le tabelle, ho ottenuto il file dei tipi e l'ho inserito nella mia app. All'improvviso cose come user.email o profile.username funzionavano e basta, senza più chiedermi se le avevo scritte giuste. È una piccola cosa, ma ha reso lo sviluppo dell'app meno simile a un gioco a indovinare e più simile a una vittoria.
Far lavorare le funzioni del database
Supabase ti permette di scrivere piccole funzioni SQL che girano nel database, ed è comodissimo. Invece di scrivere un sacco di codice lato app per modificare i dati, ho lasciato che se ne occupasse il database.
Eccone una che ho creato per aggiungere crediti al profilo di un utente:
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;
Questa prende i crediti dell'utente, ne aggiunge un po' e li salva di nuovo, tutto in un colpo solo. Senza, avrei dovuto leggere i crediti, sommarli nell'app e rimandarli indietro: più codice e più occasioni di sbagliare. Ne ho scritte alcune anche per altri compiti, e l'app è diventata più reattiva perché il lavoro pesante lo faceva il database.
L'avvertenza sul backend
Ecco il colpo di scena: Supabase non ha eliminato del tutto il mio backend. Per usare alcune funzioni di amministrazione del login serve la chiave service_role, ma non puoi metterla nell'app perché non è sicuro. Quindi ho tenuto un piccolo server NestJS per gestire quei compiti riservati. Non è grande come prima, ma c'è per tenere tutto al sicuro. Supabase fa la maggior parte del lavoro, quindi è comunque molto più semplice del mio vecchio setup.
Conclusione: ne è valsa la fatica

Migrare 182.000 utenti su Supabase non è stata solo una sfida tecnica, ma anche mentale. Tra rinvii, notti in bianco e tanti ripensamenti, ci sono stati momenti in cui ho davvero pensato di poter rompere tutto. È stata una lunga fatica, piena di stress ed esitazioni. Ma lasciarmi alle spalle il fragile setup NestJS + MongoDB e passare a qualcosa di più pulito e manutenibile ne è valsa assolutamente la pena.
Supabase mi ha dato la semplicità, la flessibilità e il supporto della community di cui avevo bisogno come sviluppatore solitario con un lavoro a tempo pieno. Se stai pensando di migrare il backend della tua app, sappi che si può fare davvero. Non sarà veloce né indolore, ma con un po' di pianificazione (e probabilmente qualche lunga nottata) arriverai dall'altra parte con un setup di cui puoi fidarti davvero.