Square CloudSquare Cloud

How to host a SaaS: frontend, API, database and domain

To host a SaaS, deploy the frontend and API, connect a database and object storage, and point a domain with HTTPS. Keep each customer's data apart with a tenant_id column and keep staging and production isolated.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Know which pieces a small SaaS needs and where each one runs
  • Separate each customer's data with tenant_id or a database per customer
  • Set up the domain, HTTPS, environment variables and a separate staging
On this page

A small SaaS looks like one project, but once you host it, it turns into six pieces: the frontend your customers open, the API with the business rules, the database, a place for files, the domain with HTTPS and the configuration that changes between staging and production. Each piece has a right way to run, and one decision in particular, how to keep each customer's data apart, is expensive to undo later.

This guide puts that architecture together for a SaaS that is just starting, with code for the part that breaks most often: isolating data per customer.

Which pieces does a small SaaS need?#

Piece What it does How it usually runs
Frontend The screens your customers use Static site (SPA) or a server-rendered app
API Business rules, authentication, billing Always-on process listening for HTTP
Database Accounts, customers, product data PostgreSQL or MySQL server, with backups
Files Uploads, attachments, exports S3-compatible object storage
Domain and HTTPS Address and certificate DNS records at your registrar, automatic TLS
Configuration Secrets and URLs per environment Environment variables, outside the code

Scheduled jobs and queues come in when the product asks for them; how they differ is covered in cron vs workers vs queues.

How do you deploy the frontend and the API?#

There are two common layouts. In the first, the frontend is a static site on app.example.com and the API runs separately on api.example.com. In the second, a full-stack framework serves the pages and the API routes from one process. The second has fewer pieces; the first lets you restart and scale the API without touching the frontend.

Either way, the API must listen on 0.0.0.0, on the port the host assigns (usually through the PORT variable), and expose a health route such as /health. The details are in how to host an API.

With the frontend and the API on different origins (different subdomains count), the browser enforces CORS: the API answers with Access-Control-Allow-Origin set to the frontend's exact origin. If the session uses cookies, the response also carries Access-Control-Allow-Credentials: true, and then the origin can't be *. Serving the API on a path of the same address (app.example.com/api), behind a proxy, removes CORS altogether.

Where do the database and the files live?#

Database. Use a database server from day one, not an SQLite file on the API's disk: with two instances or a recreated disk, that file becomes a problem. Each API instance opens a connection pool, and the total is instances times pool size; going over the server's limit triggers the error explained in too many connections. Run migrations on every deploy, before the new version takes traffic.

Files. Keep uploads in object storage and store only the object key in the database. Organize keys by customer (tenants/<tenant_id>/invoices/123.pdf) so you can list or delete everything for one customer at once. To keep files from passing through the API, the browser uploads straight to storage with a presigned URL that the API generates after checking permissions.

How do you keep each customer's data apart?#

Each customer (tenant) must see only its own data. Microsoft's multitenant SaaS patterns guide lays out the options; for a small SaaS, the choice usually comes down to two:

Shared database with tenant_id One database per customer
Isolation Logical: every query has to filter Strong: data in separate databases
Cost per customer The lowest Grows with each customer
Migrations Once Once per database
Restoring one customer Hard: the backup holds everyone Simple: just that database
Fits Many small customers A few large customers, or contracts that require isolation

The shared database is the most common starting point. Its risk is forgetting the filter in one query and showing one customer's data to another. In PostgreSQL, row-level security (RLS) adds a second lock inside the database itself:

sql
CREATE TABLE tenants (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  name text NOT NULL
);

CREATE TABLE projects (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id uuid NOT NULL REFERENCES tenants (id),
  name text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON projects (tenant_id);

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON projects
  USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
  WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);

In the API (Node.js with the pg package), each request opens a transaction and sets the customer before querying:

js
import pg from "pg";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

export async function withTenant(tenantId, fn) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
    const result = await fn(client);
    await client.query("COMMIT");
    return result;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

// usage: tenantId comes from the authenticated session, never from the request body
// const { rows } = await withTenant(session.tenantId, (db) =>
//   db.query("SELECT id, name FROM projects ORDER BY created_at DESC"),
// );

Three details from the PostgreSQL docs make this work. With true as the third argument, set_config applies only to the current transaction, so a connection returned to the pool doesn't carry the previous customer. With no value set, the comparison is null and no row passes the policy: when in doubt, the database denies. And superusers and roles with BYPASSRLS skip RLS (so does the table owner, without FORCE): the API has to connect as a regular user.

How do you set up the domain, HTTPS, variables and staging?#

Domain. At your registrar, point each subdomain at the host of the matching piece:

text
app.example.com.   CNAME   frontend.host.example.
api.example.com.   CNAME   api.host.example.

The root domain (example.com) can't take a CNAME, because a CNAME can't share its name with other records (RFC 1034), and the root already has SOA and NS. That's why many SaaS products live on app. and leave the root for the marketing site. The steps are in how to use a custom domain.

HTTPS. Every name needs a valid certificate, renewed before it expires. Most hosts issue and renew it for you; the process behind it is in how Let's Encrypt works.

Variables. Everything that changes between environments stays out of the code. Commit a .env.example with no real values:

bash
APP_URL=https://app.example.com
API_URL=https://api.example.com
DATABASE_URL=postgres://user:password@host:5432/app
S3_ENDPOINT=https://s3.provider.example
S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY=
SESSION_SECRET=

Staging. Staging is a copy of production with its own database, storage, keys and domain (staging.app.example.com), and payment keys in test mode. Deploy and migrate there first. The classic mistake is copying the production DATABASE_URL into staging. The full topic is in development, staging and production.

Can you give each customer a subdomain?#

Addresses like acme.example.com and globex.example.com make the product look polished, but they cost four things:

  1. Wildcard DNS. A *.example.com record answers for any name that has no record of its own (RFC 4592). Without it, every new customer needs a record.
  2. A wildcard certificate. A *.example.com certificate covers acme.example.com, but not a.b.example.com or example.com: the wildcard matches a single label (RFC 9525). Let's Encrypt only issues it through the DNS-01 challenge, so your ACME client needs access to your DNS provider's API.
  3. Routing in the app. The API reads the Host header, finds the customer and rejects unknown names.
  4. Isolated cookies. A cookie with Domain=example.com goes to every subdomain, which means every customer. Leave the session cookie without Domain so it stays on the host that set it (MDN).

The alternatives need none of this: the customer in the path (app.example.com/acme) or in the login, with the same URL for everyone and the tenant_id coming from the session.

What errors show up when you launch a SaaS?#

  • One customer sees another's data. A query without the tenant_id filter. RLS blocks it; a test with two sample customers catches the rest.
  • CORS error in the browser. The frontend's origin isn't on the API's list, or the API answers * with cookies (cause and fix).
  • too many connections after scaling. More instances multiplied the pools. Shrink each instance's pool.
  • Files vanish after a deploy. They were on the server disk. Move them to object storage.
  • Staging changes production data. Variables copied between environments. Check each environment's DATABASE_URL.

To confirm everything is up, curl -i https://api.example.com/health should answer 200 with a valid certificate, and two test customers should see only their own projects.

How to do this on Square Cloud#

On Square Cloud, each piece of the SaaS becomes a resource in the same account. The frontend runs as a static site (for an SPA, rename the build's index.html to vite.html and every path that isn't a file falls back to it) or as a web application, and the API is a web application listening on 0.0.0.0 on the port in the PORT variable. You deploy by ZIP upload in the dashboard, the CLI, GitHub or the VS Code extension; the squarecloud.app file is optional, since the dashboard generates it.

PostgreSQL, MySQL, MongoDB and Redis hosting starts at Standard (from R$44.99 per month, with 4 GB of RAM), in the same datacenter as your applications, with daily database snapshots. Connections require TLS: you copy the URL from the dashboard into a variable such as DATABASE_URL, and each database accepts up to 256 connections, with no pooler in front. Customer files can go to Blob, object storage with an S3-compatible API and presigned URLs, with a quota included in every plan; folders are key prefixes, like this guide's tenants/<tenant_id>/.

Every web application gets a *.squareweb.app subdomain with HTTPS. A custom domain, also from Standard, is a name like app.example.com with a CNAME to cname.squareweb.app and a validation TXT record at your registrar; the certificate is issued and renewed on its own, and the domain stays registered in your name. There is no wildcard TLS and no subdomain per customer: identify the customer by login or by path, with tenant_id in the database.

Environment variables are per application and apply on the next restart. For staging, create another application with its own variables and another database, since one application can't read another's variables or files. Team workspaces and the AI Gateway, for your product's AI features, also start at Standard. See the details in SaaS hosting.

API hosting

APIs in always-on containers, with no cold starts

SaaS hosting

FAQs

Do the frontend and the API need to share a domain?

No, but it helps. With the API on a path of the same address (/api), there is no CORS. On different subdomains, such as app. and api., the browser treats them as different origins and the API has to allow the frontend's origin.

Is a database per customer better than a tenant_id column?

For most small SaaS products, a shared database with tenant_id costs less and has a single migration path. A database per customer isolates more and makes restoring one customer easier, but it multiplies migrations, connections and cost.

Do I need a subdomain for each customer?

No. Identifying the customer from the login or from a URL path works with no extra DNS or certificate. A subdomain per customer needs a wildcard DNS record and a wildcard certificate, which Let's Encrypt only issues through the DNS-01 challenge.

Where should files uploaded by customers go?

To object storage, with the object key saved in the database. The server disk isn't shared between instances, and on many hosts it is recreated on every deploy.

Next articleHow to host a PHP (Laravel) applicationTo host a Laravel app, set APP_KEY, install without dev packages, cache the config, run migrations and serve only the public/ folder. Step by step, with config.