> ## Documentation Index
> Fetch the complete documentation index at: https://docs.shardcloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Migrate from Lovable to Shard Cloud

> Move a Lovable app (code, database, users, files and emails) to Shard Cloud, step by step.

## Introduction

This guide moves a Lovable app, including its Lovable Cloud backend, to Shard Cloud. When you finish, every piece has a new home:

| In Lovable | On Shard Cloud |
| - | - |
| Frontend (the app's code) | A Shard Cloud [application](https://docs.shardcloud.app/apps.md) |
| Database, auth (sign-up and login) and Realtime | A **Supabase** database on Shard Cloud: the same `supabase-js` calls keep working |
| Storage buckets (`supabase.storage`) | The [Shard Cloud CDN](https://docs.shardcloud.app/cdn/introduction.md) API |
| Emails | Shard Cloud email: your code sends through your [mailbox](https://shardcloud.app/dash)'s SMTP server |
| Edge functions | A small Node.js API app |

Your users keep their accounts: they log in with the same email and password they used before.

> [!WARNING]
>
> Migrating from Lovable requires at least the **Core plan**. A Supabase database needs at least **2048 MB** of RAM, plus the RAM of the apps you deploy next to it.

## Before You Start

### Where each feature runs

Everything your app uses on Lovable has a place on Shard Cloud. Auth, database and Realtime keep the same `supabase-js` code; storage and email use Shard Cloud's own APIs:

| Feature | On Shard Cloud | Code changes |
| - | - | - |
| **Auth** (`/auth/v1`): sign-up, email and password login, sessions, `getUser` | Supabase database | None |
| **Database** (`/rest/v1`): every `supabase.from(...)` call, with your row level security (RLS) policies | Supabase database | None |
| **Realtime** (`/realtime/v1`): `.channel(...)`, `postgres_changes` and broadcast | Supabase database | None |
| **Storage** (`supabase.storage`) | [Shard Cloud CDN API](https://docs.shardcloud.app/cdn/introduction.md) | Uploads go through the CDN API (step 6) |
| **Email** | Shard Cloud email (your mailbox's SMTP server) | Your code sends mail over SMTP (step 7) |
| **Edge functions** (`supabase.functions.invoke`) | A Node.js API app | Port each function to a route (step 5) |
| **Scheduled jobs** (Lovable's Jobs, `pg_cron`) | A Node.js API app | Run them on a timer in the API (step 5) |

### Not supported yet

These Lovable features have no replacement yet:

* **Emails sent by auth itself**: our Supabase auth doesn't send email. New sign-ups are confirmed automatically, and these flows **don't work**: password reset (`resetPasswordForEmail`), confirm email, magic links and email codes (`signInWithOtp`), invites (`inviteUserByEmail`), email change and reauthentication. This is only about auth's own emails: every email your app sends (welcome messages, notifications, receipts) works through Shard Cloud email (step 7).
* **Lovable AI and app connectors**: they run through Lovable (`LOVABLE_API_KEY`). Call the provider directly from your API with your own key instead.

> [!WARNING]
>
> If your app depends on password reset or magic links, plan a replacement first, or wait until we support it.

### Check your code

Download your code (step 1), then search it for the features above:

```bash theme={null}
grep -rnE "\.storage|functions\.invoke|resetPasswordForEmail|signInWithOtp|inviteUserByEmail|updateUser\(|LOVABLE_|cron\.schedule|VITE_SUPABASE_PROJECT_ID|SUPABASE_PROJECT_ID" src supabase drizzle
```

| Match | What to do |
| - | - |
| `.storage` | Switch to the Shard Cloud CDN API (step 6) |
| `functions.invoke` | Move the function to the Node.js API (step 5); its emails go through Shard Cloud email (step 7) |
| `cron.schedule`, `LOVABLE_CRON_SECRET` | Scheduled jobs: run them in the Node.js API (step 5) |
| `resetPasswordForEmail`, `signInWithOtp`, `inviteUserByEmail` | Auth emails aren't supported yet: remove or replace the flow |
| `updateUser(` with an `email` | Email change is not supported (password change works) |
| `LOVABLE_API_KEY` | Lovable AI only works inside Lovable: call your AI provider directly from the Node.js API with your own key |
| `SUPABASE_PROJECT_ID` | If the code builds a `https://<project-id>.supabase.co` address from it, use your API URL (step 3) instead |

### What you need

* A Shard Cloud account on the **Core plan** or higher
* [Docker](https://www.docker.com/) installed on your computer (it runs `pg_restore` for the database import), or, for an export up to 100 MB, a temporary Shard Cloud app instead ([step 4](#no-docker-restore-from-a-shard-cloud-app))
* [Node.js](https://nodejs.org/) 18 or newer
* A Lovable paid plan, to download the code as a zip (or GitHub sync, which works on every plan)

## Step 1: Export Your Code

Pick one:

* **GitHub**: in Lovable, connect the project to GitHub. Lovable creates a repository with your code; clone it.
* **Zip**: in the code editor, or in **Project settings → Git**, click **Download codebase**.

The code includes your database migrations (`supabase/migrations/` in older projects, `drizzle/migrations/` in newer ones) and your edge functions (`supabase/functions/`), but no data and no files.

> [!NOTE]
>
> After you move, keep editing the app in your own editor (or Claude Code, Cursor, etc.). A Lovable Cloud project can't be switched to an outside backend, so the Lovable editor stays on the old one.

## Step 2: Export Your Database and Files

### Database

**1. Start the export**

In Lovable, open **More → Database → Manage → Settings**. Under **Export project data**, click **Export data**, then **Export**, then **Start export**.

**2. Wait for the email**

Lovable emails you when the export is ready and saves it to your project's storage.

**3. Download it**

Download the file from **More → Storage** and keep it on your computer. If it comes as a `.zip`, extract it. Rename the `.backup` file inside to `lovable.backup`.

The export holds your tables, your RLS policies, and your users' accounts with their password hashes. It doesn't hold storage files, edge function code, secrets, sign-in provider settings or scheduled jobs. Lovable allows one export every 24 hours, only while the database is running: resume a paused project first. Exports work for databases up to 15 GB.

> [!NOTE]
>
> The import below needs Lovable's `.backup` file (a compressed PostgreSQL custom-format archive). If you got a plain `.sql` file instead, contact us on [Discord](https://discord.gg/jjdYayFu5Q) before you continue.

### Storage files

The database export does **not** include files in storage. In Lovable, open **More → Storage**, open each bucket, select its files and download them (several files download as one zip). Put them in a folder on your computer, with one subfolder per bucket:

```
lovable-files/
├── avatars/
│   ├── 3f2a....png
│   └── ...
└── documents/
    └── ...
```

> [!WARNING]
>
> Download the database export and your files **before** you remove Lovable Cloud from the project. Files saved in Lovable's storage are gone after that.

### Secrets

Secrets (API keys you added in Lovable, such as Stripe keys) are not exported either, and Lovable never shows a secret's value again after you save it. Note the names in **More → Settings → Secrets**, then get each value again from the service that issued it (Stripe's dashboard, for example): you will put them in the Node.js API app.

### Scheduled jobs

Note the jobs listed in **More → Database → Manage → Jobs**: their schedule (like `0 * * * *`) and the edge function or API route each one calls. They don't come with the export.

## Step 3: Create Your Supabase Database

**1. Create the database**

In the [Shard Cloud Dashboard](https://shardcloud.app/dash), create a new database and choose **Supabase** as the type, with at least **2048 MB** of RAM.

**2. Wait for it to start**

The first start takes about a minute. Until it's ready, the API URL answers with an error page.

**3. Copy the connection details**

On the database page, copy:

* The **API URL**, like `https://apiview-postgres-<id>.shardweb.app`
* The **anon key** (public: it goes into your frontend)
* The **database host**, like `postgres-<id>.shardatabases.app`, the **user** and the **password**

> [!WARNING]
>
> The page also shows a **service\_role key**. It bypasses row level security: never put it in your frontend.

## Step 4: Import Your Database

Import into the **new, empty** database you just created: the import doesn't delete anything first.

The import runs in two passes, in this order:

1. The `auth` schema, data only: your users and their password hashes. Our Supabase already created the `auth` tables, so only the rows are copied.
2. The `public` schema, in full: your tables, data, functions, RLS policies, grants and Realtime settings.

Users go first because your tables' foreign keys to `auth.users` (a `profiles` table, for example) can only be created once the users exist. In the other order, `pg_restore` copies the rows but skips those foreign keys, with only an error in its output to show it.

Run these commands from the folder that holds `lovable.backup` (on Windows, use Git Bash or WSL). Replace the values with the ones from step 3:

```bash theme={null}
export PGPASSWORD='your-database-password'
CONN="host=postgres-<id>.shardatabases.app port=5432 dbname=postgres user=<user> sslmode=require"
```

**Pass 1: your users**

List the `auth` tables that have data, except `schema_migrations` (our Supabase manages that one):

```bash theme={null}
AUTH_TABLES=$(docker run --rm -i postgres:18 pg_restore --format=custom --list < lovable.backup | awk '$4 == "TABLE" && $5 == "DATA" && $6 == "auth" && $7 != "schema_migrations" { printf "--table=%s ", $7 }')
echo "$AUTH_TABLES"
```

Then copy their rows:

```bash theme={null}
docker run --rm -i -e PGPASSWORD postgres:18 pg_restore --format=custom --dbname="$CONN" --data-only --schema=auth --disable-triggers $AUTH_TABLES < lovable.backup
```

**Pass 2: the `public` schema**

```bash theme={null}
docker run --rm -i -e PGPASSWORD postgres:18 pg_restore --format=custom --dbname="$CONN" --schema=public < lovable.backup
```

### No Docker? Restore from a Shard Cloud app

You can run the same import on Shard Cloud instead, in a small temporary app. It needs no Docker on your computer, and it connects with your database's own user and password. It works for an export up to **100 MB** (the app upload limit); for a bigger one, use Docker as above.

**1. Make a folder for the app**

Put three files in an empty folder: your `lovable.backup`, the `restore.sh` script below, and this `.shardcloud`:

```systemd .shardcloud theme={null}
DISPLAY_NAME=Lovable Restore
LANGUAGE=node
MEMORY=512
VERSION=recommended
CUSTOM_COMMAND=sh restore.sh; sleep infinity
```

**2. Upload it**

Zip the folder and upload it in the [Dashboard](https://shardcloud.app/dash/applications). Its first start logs `Set the PGHOST environment variable first`: that is expected.

**3. Give it the connection**

In the app's environment variables in the dashboard, add the values from step 3, then restart the app:

* `PGHOST`: the database host
* `PGUSER`: the database user
* `PGPASSWORD`: the database password
* `PGDATABASE`: `postgres`
* `PGSSLMODE`: `require`

**4. Read the result**

The app's logs show both passes and a check at the end: the number of users, your tables and their foreign keys to `auth.users`. The script runs once: it leaves a `restore.done` file, so a restart doesn't import the data a second time.

**5. Delete the app**

Once the import is checked, delete the app: it holds your export, with your users' password hashes.

```bash restore.sh theme={null}
#!/bin/sh
# Restores a Lovable database export (lovable.backup, in this folder) into
# your Shard Cloud Supabase database. The connection comes from the PGHOST,
# PGUSER, PGPASSWORD, PGDATABASE and PGSSLMODE environment variables.
BACKUP=lovable.backup

for v in PGHOST PGUSER PGPASSWORD PGDATABASE; do
  eval "value=\$$v"
  [ -n "$value" ] || { echo "Set the $v environment variable first"; exit 1; }
done
[ -f "$BACKUP" ] || { echo "$BACKUP not found in $(pwd)"; exit 1; }
# Runs once: a restart must not import the same data twice.
[ -f restore.done ] && { echo "Already restored (restore.done exists): nothing to do"; exit 0; }

# Lovable's export needs pg_restore 18 or newer. If this machine has an older
# one, download the PostgreSQL 18 client from the PostgreSQL apt repository
# and unpack it here (no installation, no root needed).
BIN=$(dirname "$(command -v pg_restore || echo /none/pg_restore)")
MAJOR=$("$BIN/pg_restore" --version 2>/dev/null | sed -n 's/.* \([0-9][0-9]*\)\..*/\1/p')
if [ "${MAJOR:-0}" -lt 18 ]; then
  echo "== Downloading the PostgreSQL 18 client =="
  CODENAME=$(. /etc/os-release && echo "$VERSION_CODENAME")
  REPO=https://apt.postgresql.org/pub/repos/apt
  mkdir -p pg18 && cd pg18 || exit 1
  curl -fsSL "$REPO/dists/$CODENAME-pgdg/main/binary-amd64/Packages.gz" | gunzip > Packages || exit 1
  for PKG in postgresql-client-18 libpq5; do
    FILE=$(awk -v p="$PKG" '$1 == "Package:" { name = $2 } $1 == "Filename:" && name == p { print $2 }' Packages | sort -V | tail -n 1)
    [ -n "$FILE" ] || { echo "Could not find $PKG in the repository"; exit 1; }
    curl -fsSL -o "$PKG.deb" "$REPO/$FILE" && dpkg-deb -x "$PKG.deb" root || exit 1
  done
  cd ..
  export LD_LIBRARY_PATH="$PWD/pg18/root/usr/lib/x86_64-linux-gnu"
  BIN="$PWD/pg18/root/usr/lib/postgresql/18/bin"
fi
"$BIN/pg_restore" --version || exit 1
"$BIN/psql" -Atc "select 'Connected to ' || current_database()" || { echo "Could not connect: check the PG* variables"; exit 1; }
touch restore.done

# Users first: your tables' foreign keys to auth.users (a profiles table,
# for example) can only be created once the users are there.
echo "== Pass 1: your users (auth schema, data only) =="
AUTH_TABLES=$("$BIN/pg_restore" --format=custom --list "$BACKUP" | awk '$4 == "TABLE" && $5 == "DATA" && $6 == "auth" && $7 != "schema_migrations" { printf "--table=%s ", $7 }')
"$BIN/pg_restore" --format=custom --dbname="$PGDATABASE" --data-only --schema=auth --disable-triggers $AUTH_TABLES "$BACKUP"
echo "Pass 1 exit code: $?"

echo "== Pass 2: the public schema =="
"$BIN/pg_restore" --format=custom --dbname="$PGDATABASE" --schema=public "$BACKUP"
echo "Pass 2 exit code: $?"

echo "== Check =="
"$BIN/psql" -c "notify pgrst, 'reload schema';" \
  -c "select count(*) as users from auth.users;" \
  -c "\dt public.*" \
  -c "select conrelid::regclass as foreign_keys_to_auth_users from pg_constraint where contype = 'f' and confrelid = 'auth.users'::regclass and connamespace = 'public'::regnamespace;" \
  -c "select tgname as auth_users_triggers from pg_trigger where tgrelid = 'auth.users'::regclass and not tgisinternal;"
```

> [!NOTE]
>
> An exit code of 1 means `pg_restore` skipped something and printed why just above it. Read those errors before you go on: a message about a role that doesn't exist is usually harmless, a failed foreign key or table is not.

### Re-create your triggers on `auth.users`

Many Lovable apps create a row in `public.profiles` whenever someone signs up, through a trigger on `auth.users` (often named `on_auth_user_created`). That trigger lives in the `auth` schema, so the data-only pass above does not bring it.

List the triggers in your export:

```bash theme={null}
docker run --rm -i postgres:18 pg_restore --format=custom --list < lovable.backup | grep TRIGGER
```

Then find their `CREATE TRIGGER` statements in your code:

```bash theme={null}
grep -rn "ON auth.users" supabase/migrations drizzle
```

Connect to the database (with `psql`, or the database visualizer in the dashboard) and run each `CREATE TRIGGER ... ON auth.users ...` statement you found. For example:

```sql theme={null}
CREATE TRIGGER on_auth_user_created
  AFTER INSERT ON auth.users
  FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
```

The function itself (`public.handle_new_user`) was already imported with the `public` schema (pass 2).

### Check the import

Run these queries on the database:

```sql theme={null}
-- Your users came over
select count(*) from auth.users;


-- Your triggers on auth.users exist again
select tgname from pg_trigger where tgrelid = 'auth.users'::regclass and not tgisinternal;

-- Make the API see the imported tables right away
notify pgrst, 'reload schema';
```

> [!NOTE]
>
> Users keep their accounts and passwords, but not their sessions: everyone logs in once more after the move.

> [!TIP]
>
> If some users never confirmed their email on Lovable, they may not be able to log in. Since our Supabase doesn't send confirmation emails, you can mark them as confirmed:
> `update auth.users set email_confirmed_at = now() where email_confirmed_at is null;`
> Only do this if you trust those addresses.

## Step 5: Create the Node.js API

Edge functions don't run on our Supabase, and the CDN token and the SMTP password must never reach the browser. So the code that used to run in edge functions moves to a small Node.js API app. It checks the user's Supabase session, then does the work on their behalf.

> [!TIP]
>
> Newer Lovable apps (TanStack Start) already have their own server, with server functions and API routes instead of edge functions. You can put the code below in those API routes and skip the separate API app.

### Create the project

```bash theme={null}
mkdir my-app-api
cd my-app-api
npm init -y
npm install express cors multer nodemailer dotenv node-cron @supabase/supabase-js
```

### Environment variables

Create a `.env` file. Put the secrets you copied from Lovable here too:

```bash .env theme={null}
SUPABASE_URL=https://apiview-postgres-<id>.shardweb.app
SUPABASE_ANON_KEY=your-anon-key
FRONTEND_URL=https://myapp.shardweb.app

# Shard Cloud CDN (Dashboard → Config → Integrations)
SHARD_API_TOKEN=your-api-token

# Shard Cloud mailbox (connection details on the mailbox page)
SMTP_HOST=your-mailbox-smtp-host
SMTP_PORT=465
SMTP_USER=contact@yourdomain.com
SMTP_PASS=your-mailbox-password
```

### The server

```javascript server.js theme={null}
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const nodemailer = require('nodemailer');
const crypto = require('crypto');
const cron = require('node-cron');
const { createClient } = require('@supabase/supabase-js');

const app = express();
app.use(cors({ origin: process.env.FRONTEND_URL }));
app.use(express.json());

const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY);
const upload = multer({ limits: { fileSize: 100 * 1024 * 1024 } });

const mailer = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT),
  secure: Number(process.env.SMTP_PORT) === 465,
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});

// Accepts only requests from a logged-in user of your app.
async function requireUser(req, res, next) {
  const token = (req.headers.authorization || '').replace('Bearer ', '');
  const { data, error } = await supabase.auth.getUser(token);
  if (error || !data.user) return res.status(401).json({ error: 'Not logged in' });
  req.user = data.user;
  next();
}

// Replaces supabase.storage.from(folder).upload(...)
app.post('/upload', requireUser, upload.single('file'), async (req, res) => {
  const form = new FormData();
  form.append('file', new Blob([req.file.buffer], { type: req.file.mimetype }));
  // A random name, so nobody can guess another user's file URL.
  // CDN names: letters, numbers, _ and -, up to 64 characters, no extension
  form.append('filename', crypto.randomUUID().replace(/-/g, ''));
  form.append('folder', req.body.folder || 'uploads');

  const response = await fetch('https://shardcloud.app/api/cdn/files', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.SHARD_API_TOKEN}` },
    body: form,
  });
  const file = await response.json();
  if (!response.ok) return res.status(response.status).json(file);
  res.json({ url: file.url });
});

// An example of an email your app sends
app.post('/send-welcome', requireUser, async (req, res) => {
  await mailer.sendMail({
    from: process.env.SMTP_USER,
    to: req.user.email,
    subject: 'Welcome!',
    text: 'Thanks for joining.',
  });
  res.json({ ok: true });
});

// Replaces a Lovable scheduled job: runs every hour, like the cron "0 * * * *"
cron.schedule('0 * * * *', async () => {
  console.log('hourly job');
});

app.listen(80, () => console.log('API running on port 80'));
```

Port each edge function from `supabase/functions/` to a route like the ones above. Edge functions are written for Deno, so change `Deno.env.get('X')` to `process.env.X` and `serve(async (req) => ...)` to an Express route.

Port each scheduled job to a `cron.schedule(...)` with the same schedule, calling the code its edge function or API route ran. Lovable's `LOVABLE_CRON_SECRET` check isn't needed: the job now runs inside your API. Keep the API at a single instance, or each job runs once per instance.

### Deploy it

```systemd .shardcloud theme={null}
DISPLAY_NAME=My App API
LANGUAGE=node
MAIN=server.js
MEMORY=512
VERSION=recommended
SUBDOMAIN=myappapi
```

Zip the project without `node_modules/` and upload it in the [Dashboard](https://shardcloud.app/dash/applications). The API is then at `https://myappapi.shardweb.app`.

## Step 6: Move Storage to the CDN

### Upload your existing files

This script uploads every file from the folder you downloaded in step 2 and writes `cdn-map.json`, which maps each old path to its new CDN URL. Run it on your computer:

```javascript migrate-files.js theme={null}
const fs = require('fs');
const path = require('path');

const TOKEN = process.env.SHARD_API_TOKEN;
const ROOT = process.argv[2] || 'lovable-files';
const MIME = {
  '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
  '.webp': 'image/webp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf',
  '.mp4': 'video/mp4', '.json': 'application/json', '.txt': 'text/plain', '.csv': 'text/csv',
};

// CDN names: letters, numbers, _ and -, up to 64 characters, no extension
function cdnName(file, used) {
  let name = path.parse(file).name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 56) || 'file';
  let candidate = name;
  for (let i = 1; used.has(candidate); i++) candidate = `${name}_${i}`;
  used.add(candidate);
  return candidate;
}

async function main() {
  const map = {};
  for (const bucket of fs.readdirSync(ROOT)) {
    const used = new Set();
    const dir = path.join(ROOT, bucket);
    for (const file of fs.readdirSync(dir, { recursive: true })) {
      const full = path.join(dir, file);
      if (fs.statSync(full).isDirectory()) continue;
      const type = MIME[path.extname(file).toLowerCase()];
      if (!type) { console.log(`skipped (unknown type): ${full}`); continue; }

      const form = new FormData();
      form.append('file', new Blob([fs.readFileSync(full)], { type }));
      form.append('filename', cdnName(file, used));
      form.append('folder', bucket.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64));

      const res = await fetch('https://shardcloud.app/api/cdn/files', {
        method: 'POST',
        headers: { Authorization: `Bearer ${TOKEN}` },
        body: form,
      });
      const body = await res.json();
      if (!res.ok) { console.log(`failed: ${full}`, body); continue; }
      map[`${bucket}/${file.split(path.sep).join('/')}`] = body.url;
      console.log(`${full} -> ${body.url}`);
    }
  }
  fs.writeFileSync('cdn-map.json', JSON.stringify(map, null, 2));
}

main();
```

```bash theme={null}
SHARD_API_TOKEN=your-api-token node migrate-files.js lovable-files
```

> [!NOTE]
>
> The CDN accepts files from **2 KB** to **100 MB** in a single request (bigger files: see [large file uploads](https://docs.shardcloud.app/cdn/introduction.md#large-file-uploads)), of the [supported file types](https://docs.shardcloud.app/cdn/supported-file-types.md). The script prints every file it skipped or that failed, so you can handle those by hand.

### Update the links in your database

If your tables store Lovable storage URLs (like `https://<project>.supabase.co/storage/v1/object/public/avatars/abc.png`) or paths (like `avatars/abc.png`), replace them with the URLs in `cdn-map.json`. For example, for an `avatar_url` column:

```sql theme={null}
update public.profiles
set avatar_url = 'https://new-cdn-url-from-cdn-map.png'
where avatar_url like '%/avatars/abc.png';
```

For many files, generate these `update` statements from `cdn-map.json` with a small script.

### Change the upload code

Replace each `supabase.storage` upload in your frontend with a call to your API, and save the returned URL instead of a storage path:

```typescript Before theme={null}
const { data } = await supabase.storage.from('avatars').upload(`${user.id}/avatar.png`, file);
const { data: { publicUrl } } = supabase.storage.from('avatars').getPublicUrl(data.path);
```

```typescript After theme={null}
const { data: { session } } = await supabase.auth.getSession();
const form = new FormData();
form.append('file', file);
form.append('folder', 'avatars');

const res = await fetch('https://myappapi.shardweb.app/upload', {
  method: 'POST',
  headers: { Authorization: `Bearer ${session.access_token}` },
  body: form,
});
const { url: publicUrl } = await res.json();
```

> [!WARNING]
>
> Lovable buckets are **private** by default: their files are protected by row level security and shared through signed links (`createSignedUrl`) that expire after an hour. Every CDN file is reachable by anyone who has its URL. The random names above make URLs impossible to guess, but anyone a URL is shared with can open it. For truly private files (contracts, IDs, invoices), keep them behind your API instead of putting them on the CDN, or use the CDN's `expire_at` for files that only need to live for a while.

## Step 7: Send Emails Through Shard Cloud Email

Your app's emails go through Shard Cloud email: your code connects to your mailbox's SMTP server and sends the mail.

**1. Create a mailbox**

In the [Dashboard](https://shardcloud.app/dash), buy a mailbox, verify your domain and set up an address, such as `contact@yourdomain.com`.

**2. Add the DNS records**

Add the MX, SPF, DKIM and DMARC records the dashboard shows (one click if your domain uses Shard Cloud DNS), so your mail doesn't land in spam.

**3. Copy the SMTP details**

On the mailbox page, copy the SMTP host, port (`465`, TLS), username and password into the API's `.env` (step 5).

**4. Send from your API**

Use `mailer.sendMail(...)` as in the `/send-welcome` route. Move every email your app sent (through Lovable's built-in app emails, or a provider such as Resend) there.

> [!NOTE]
>
> Each mailbox has an hourly sending limit that depends on its plan (75, 150 or 250 emails per hour). It's made for your app's transactional emails, not for newsletters or bulk mail.

Then call the route from your frontend instead of `supabase.functions.invoke(...)`:

```typescript theme={null}
const { data: { session } } = await supabase.auth.getSession();
await fetch('https://myappapi.shardweb.app/send-welcome', {
  method: 'POST',
  headers: { Authorization: `Bearer ${session.access_token}` },
});
```

## Step 8: Point Your Frontend to Shard Cloud

Open the `.env` file at the root of your Lovable code and set your new Supabase database:

```bash .env theme={null}
VITE_SUPABASE_URL=https://apiview-postgres-<id>.shardweb.app
VITE_SUPABASE_PUBLISHABLE_KEY=your-anon-key

# TanStack Start apps only: the same values for the app's server code
SUPABASE_URL=https://apiview-postgres-<id>.shardweb.app
SUPABASE_PUBLISHABLE_KEY=your-anon-key
```

Leave `VITE_SUPABASE_PROJECT_ID` and `SUPABASE_PROJECT_ID` as they are, unless the check in "Before You Start" found code that builds a `supabase.co` address from them.

> [!NOTE]
>
> Older Lovable projects write the URL and key directly in `src/integrations/supabase/client.ts` instead. Replace them there:
>
> ```typescript src/integrations/supabase/client.ts theme={null}
> const SUPABASE_URL = "https://apiview-postgres-<id>.shardweb.app";
> const SUPABASE_PUBLISHABLE_KEY = "your-anon-key";
> ```

Nothing else changes in your `supabase.from(...)`, `supabase.auth` and `supabase.channel(...)` code.

## Step 9: Deploy Your Frontend

Lovable apps come in two kinds. Check `package.json`:

> [tab] Vite + React (most apps)
>
> The app builds to static files in `dist/`. Create a `.shardcloud` file:
>
> ```systemd .shardcloud theme={null}
> DISPLAY_NAME=My App
> LANGUAGE=node
> MEMORY=512
> VERSION=recommended
> SUBDOMAIN=myapp
> CUSTOM_COMMAND=npm run build && npx serve -s dist -l 80
> ```
>
> See the [Vite tutorial](https://docs.shardcloud.app/tutorials/website/vite.md) for more options.

> [tab] TanStack Start
>
> If `package.json` uses `@tanstack/react-start`, the app has its own server. Lovable configures it for Cloudflare, so build it for Node instead:
>
> ```systemd .shardcloud theme={null}
> DISPLAY_NAME=My App
> LANGUAGE=node
> MEMORY=512
> VERSION=recommended
> SUBDOMAIN=myapp
> CUSTOM_COMMAND=NITRO_PRESET=node-server npm run build && PORT=80 node --env-file=.env .output/server/index.mjs
> ```
>
> `--env-file=.env` gives the server code its `SUPABASE_*` values at runtime (the build only bakes in the `VITE_*` ones). Don't use an `index.html` fallback for this kind of app: its server handles every route.

Zip the project without `node_modules/` and `dist/`, and upload it in the [Dashboard](https://shardcloud.app/dash/applications). To use your own domain, see [Custom Domain](https://docs.shardcloud.app/tutorials/platform/custom-domain.md).

## Step 10: Test Everything

**1. Log in as an existing user**

Use an account from Lovable with its old password, and check that it sees its own data (your RLS policies).

**2. Sign up a new user**

Check that the profile row your trigger creates appears in `public.profiles`.

**3. Upload a file**

Check that it gets a CDN URL and shows in the app.

**4. Send an email**

Check that it arrives, and not in spam.

**5. Open the app in two browsers**

If your app uses Realtime, check that a change made in one shows up in the other.

## Step 11: Switch Over

Do a test run of steps 2 to 10 first, and time the export and import. Then move for real:

**1. Stop writes on Lovable**

Pause sign-ups and changes in the Lovable app (or tell your users), so no data is written after the final export.

**2. Take the final export**

Export the database again (step 2) and download any files added since your test run. Remember: one export every 24 hours.

**3. Import into a new database**

Create a fresh Supabase database and repeat steps 4 and 6, then update the API URL and anon key in your apps.

**4. Point your domain to Shard Cloud**

See [Custom Domain](https://docs.shardcloud.app/tutorials/platform/custom-domain.md).

**5. Retire Lovable**

Turn off the scheduled jobs on Lovable, so they don't run twice. Unpublish the app, so the `lovable.app` address stops serving the old version. Only remove the Lovable Cloud backend once you've checked your downloads: that deletes its exports and files too.

## Troubleshooting

> [accordion] The app shows CORS or network errors
>
> * Check that `VITE_SUPABASE_URL` is the API URL from the database page, with no `/rest/v1` at the end.
> * Rebuild the frontend after changing `.env`: Vite writes the values into the build.
> * For the Node.js API, check that `FRONTEND_URL` is exactly your app's address.

> [accordion] Could not find the table in the schema cache
>
> The API hasn't seen a new table yet. Run `notify pgrst, 'reload schema';` on the database.

> [accordion] Old users get invalid credentials
>
> Check that pass 1 of the import (your users) ran: `select count(*) from auth.users;`

> [accordion] Users are logged out after the move
>
> This is expected: sessions don't carry over. Users log in again with their old password.

> [accordion] New users have no profile
>
> The trigger on `auth.users` is missing. Re-create it as shown in step 4.

> [accordion] Password reset emails never arrive
>
> Supabase auth's own emails aren't supported yet, so password reset, magic links and email confirmation don't work. The request answers as if it worked, but no email is sent. Emails your code sends through Shard Cloud email (step 7) are not affected.

> [accordion] pg\_restore errors on the import
>
> * Import into a new, empty database: the import never drops anything first.
> * Use the `postgres:18` image, as in the commands above: Lovable's export is compressed in a way older `pg_restore` versions can't read.

> [accordion] CDN upload fails
>
> * Files must be between 2 KB and 100 MB and of a [supported type](https://docs.shardcloud.app/cdn/supported-file-types.md).
> * Names may only use letters, numbers, `_` and `-`, up to 64 characters, with no extension.

## Additional Resources

* [Lovable: back up, restore and export your database](https://docs.lovable.dev/features/database-backups)
* [Lovable: sync your project with GitHub](https://docs.lovable.dev/integrations/github)
* [Lovable: deploying and hosting outside Lovable](https://docs.lovable.dev/tips-tricks/external-deployment-hosting)
* [Shard Cloud CDN](https://docs.shardcloud.app/cdn/introduction.md)
* [Database services](https://docs.shardcloud.app/databases.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.