What an ephemeral environment is, how it differs from a shared staging environment, what has to be inside one for it to be useful, how teams handle data, secrets and cost, and a TypeScript example where every pull request gets its own environment with a database and Pub/Sub.

A shared staging environment works while a few people deploy to it. With a dozen open pull requests it turns into a queue, and two branches that change the same table overwrite each other's work.
Ephemeral environments give each change its own short-lived copy of the app. This guide explains what goes into one and how to build it.
An ephemeral environment is an isolated, short-lived deployment of an application, created automatically for a single change, usually a pull request, and destroyed when that change is merged or closed. It runs the branch's code against its own databases, queues and storage, so a reviewer can click through the change and an automated test can hit a live URL without touching anything shared.
Staging is long-lived and shared, so its state is the sum of every change ever deployed to it, including migrations from branches that never merged and test data nobody remembers creating. An ephemeral environment starts from a known state every time, which makes a failure in it a signal about the change under review instead of about staging's history.
Most teams keep both, with ephemeral environments carrying the review of individual changes, and staging remaining the place where merged code meets production-like configuration, scale and integrations before release, which is closer to the dev/prod parity the twelve-factor methodology argues for.
Everything the change touches has to be in the environment or the test proves little, which in practice means the services, their databases and the queues or topics between them. A preview that shares a database with staging is only half isolated, since its migrations change the schema for everyone and its test data shows up in staging.
Each third-party integration needs its own decision, and since payment providers and email services usually offer test modes or sandbox keys, preview environments get their own secret values pointing at those, and outbound effects such as sending email to real addresses are switched off by checking the environment type in code. Scheduled jobs often do not run in previews at all, and the job's endpoint is called by hand when a reviewer needs it.
Most teams start each environment from migrations plus a small seed, which is fast and contains no customer data. When reviewers need realistic volume, the environment can start from a copy of a staging database, and Postgres can create a database from an existing one with CREATE DATABASE ... TEMPLATE, while managed services offer snapshots and copy-on-write branching for larger copies.
Copying production data into ephemeral environments brings personal data into places with weaker access controls, so it usually needs a scrubbing step first. A staging database filled with generated data avoids that question entirely.
Cost comes from environments that outlive their pull requests and from giving each one production-sized resources. Tie teardown to the pull request's closed event, which GitHub sends for both merged and abandoned pull requests, as the pull_request event docs describe, and add a scheduled sweep for environments whose teardown job failed.
Small resources go a long way, since a preview serves a few reviewers rather than customers. On Kubernetes, a ResourceQuota per namespace caps what one pull request can use, and sharing one database server with a database per pull request keeps the number of managed instances flat.
The common setup on Kubernetes creates a namespace named after the pull request, installs the app's Helm chart into it with an image tagged by commit, creates a database on a shared server, and posts the URL back to the pull request. The pieces are standard, and the work is in the glue: DNS or ingress rules per namespace, secrets copied into each namespace, migrations run before the pods start, and a cleanup path that also works when CI fails.
The infrastructure as code route gives each pull request a full copy of the stack, which is the most faithful option and the slowest to create, since managed databases and load balancers take minutes to provision and add cost for every open pull request.
Encore brings infrastructure from code, so the environment it creates for a pull request contains exactly what that branch declares, whether that is a new database, a new Pub/Sub topic or a bucket, with nothing to update in a separate stack. Once the app is linked to GitHub, each pull request gets a preview environment hosted by Encore, named after the pull request, such as pr:72, with its API at https://pr72-$APP_ID.encr.app, and the environment is destroyed when the pull request is merged or closed.

Run in your terminal to get started locally.
In the example below, a signup service stores accounts in its own database and publishes an event that a subscriber turns into a welcome email. The migration creates both tables:
-- signup/migrations/1_create_tables.up.sql
CREATE TABLE accounts (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE welcome_emails (
account_id BIGINT PRIMARY KEY REFERENCES accounts (id),
sent_to TEXT NOT NULL,
delivered BOOLEAN NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
The service definition gives the directory its name:
// signup/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("signup");
The subscriber checks the environment type with the metadata API, so a preview records the email instead of sending it, and the welcome_emails primary key plus an idempotency key on the Resend request keep a redelivered message from sending twice:
// signup/signup.ts
import { appMeta } from "encore.dev";
import { api } from "encore.dev/api";
import { secret } from "encore.dev/config";
import { Subscription, Topic } from "encore.dev/pubsub";
import { SQLDatabase } from "encore.dev/storage/sqldb";
// Every preview environment gets its own copy of this database and topic.
const db = new SQLDatabase("signup", { migrations: "./migrations" });
interface SignupEvent {
accountId: number;
email: string;
}
export const signups = new Topic<SignupEvent>("signups", {
deliveryGuarantee: "at-least-once",
});
// Set per environment type, so previews can use a test key.
const emailAPIKey = secret("EmailAPIKey");
export const signup = api(
{ expose: true, method: "POST", path: "/signup" },
async ({ email }: { email: string }): Promise<{ accountId: number }> => {
const row = await db.queryRow<{ id: number }>`
INSERT INTO accounts (email) VALUES (${email})
ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email
RETURNING id
`;
if (!row) throw new Error("insert returned no row");
await signups.publish({ accountId: row.id, email });
return { accountId: row.id };
},
);
const _ = new Subscription(signups, "send-welcome-email", {
handler: async (event) => {
// Skip accounts that already got their welcome email (redelivery).
const done = await db.queryRow`
SELECT 1 FROM welcome_emails WHERE account_id = ${event.accountId}
`;
if (done) return;
// Preview environments have type "ephemeral": never email real addresses from them.
const deliver = appMeta().environment.type !== "ephemeral";
if (deliver) {
const res = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${emailAPIKey()}`,
"Content-Type": "application/json",
// Resend drops a repeat of the same key, which covers a crash after the send.
"Idempotency-Key": `welcome-${event.accountId}`,
},
body: JSON.stringify({
from: "hello@example.com",
to: event.email,
subject: "Welcome",
text: "Thanks for signing up.",
}),
});
if (!res.ok) throw new Error(`email API returned ${res.status}`);
}
await db.exec`
INSERT INTO welcome_emails (account_id, sent_to, delivered)
VALUES (${event.accountId}, ${event.email}, ${deliver})
ON CONFLICT (account_id) DO NOTHING
`;
},
});
Secret values are set per environment type, and encore secret set --type preview EmailAPIKey gives every pull request the same test key while production keeps its own value, as the secrets docs describe, and a deploy fails if a secret the code uses has no value for that environment type. Cron jobs do not run in preview environments, so a scheduled job in the branch is tested by calling its endpoint directly.
Each preview database starts empty with the branch's migrations applied, or from a copy of another environment's database, such as staging, chosen under App Settings in the Platform Dashboard, which uses Neon's database branching and requires Neon as the database provider. When the pull request changes the API, encore gen client --env=pr:72 --lang=typescript my-app gives a frontend developer a typed client for that preview.
A coding agent declares a new database or topic in the same code change as the logic that uses it and runs it locally with encore run, so its pull request gets a preview with that infrastructure already in place, and a reviewer can try the change at a URL before reading the diff in detail.
Best fit: Teams that want every pull request to come with its own isolated backend, including the databases and topics it declares, at a URL reviewers can open.
An ephemeral environment is a short-lived, isolated copy of an application, usually created automatically for one pull request and destroyed when the pull request is merged or closed. It runs the branch's code with its own databases and queues, so reviewers can test a change without sharing staging with everyone else.
Staging is one long-lived environment that every change passes through, so changes wait for it or collide in it. An ephemeral environment exists for one change, starts from a known state, and disappears with the pull request, which removes the queue and the cleanup that a shared staging environment needs.
Yes. The terms are used for the same idea, and preview environment is the more common name when the environment is tied to a pull request. Some teams also use ephemeral environments for load tests or demos that are not linked to a pull request.
Link the app to GitHub, and Encore creates a preview environment for each pull request, named after it, such as pr:72, with the databases, Pub/Sub topics and buckets the branch declares in code. The environment type is ephemeral, so code can check appMeta().environment.type, and the environment is destroyed when the pull request is merged or closed.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.