Thuta Learning
Next.js
AdvancedWeb DevelopmentIntermediate

Production Deployment to Vercel

Next.jsLesson 2635 min

What you'll walk away with

  • Explain how a Git push turns into preview and production deployments
  • Keep variables and databases separate for the Production, Preview and Development environments
  • Trace which commit and which variables each deployment uses
  • Smoke-test after every deploy and return to a previous deployment when something breaks

Explain it simply

Explain it simply

Think of a publishing house. Every time the author makes changes, the editor gets a proof copy to review: that is a preview deployment. Only when the editor approves does the real book go to the shops: that is a production deployment.

Printing the book is not the end. You need to know which edition went out and how to bring back the previous one if a mistake turns up. Deploying is not just one command succeeding; it is being able to answer those questions.

Problem → Why → Solution

The problem: a preview deleted production data

A team set DATABASE_URL to a single value for every environment. A developer writes an experimental "delete all notes" admin feature on a branch and pushes it. When the preview URL arrives, they click the button to try it.

The preview deployment was connected to the production database, so real users' notes disappear. On top of that, nobody can say straight away which commit production is running or where the backup is.

Environment variables (dashboard)
Key            Value                                   Environments
DATABASE_URL   postgres://app@prod-db.internal/notes   Production, Preview, Development
AUTH_SECRET    (one shared secret)                     Production, Preview, Development

Why is this setup dangerous?

Preview deployments exist to run unfinished, unreviewed code. Give that code the production database and secrets, and every experiment can hurt real users. Only with a separate database and secrets per environment can previews be tried freely.

Core concept: the Git-based deployment flow

Vercel is a hosting platform from the company that created Next.js, and it can deploy Next.js apps without any server setup. Other platforms support Next.js too, and the next lesson covers self-hosting with Docker. The ideas you learn here (previews, separate environments, smoke tests and rollback) apply whichever platform you use.

When you import a GitHub, GitLab or Bitbucket repository, Vercel detects the framework and sets the build command. In a monorepo you must pick the root directory that holds the Next.js app yourself. From then on, deploying is just git push.

text
From push to production
-----------------------
git push feature/tags ──> build ──> Preview  (unique URL per deployment)
                                     uses Preview variables + test DB
        │
        │ pull request reviewed, merged into main
        ▼
git push main ─────────> build ──> Production (your domain)
                                     uses Production variables + prod DB
        │
        ▼
smoke test passes? ── no ──> roll back to the previous deployment

Each environment variable can be assigned to any of three environments: Production, Preview and Development. Give DATABASE_URL different values: the production database for Production and a test database for Preview. A changed variable only takes effect in a new deployment, so redeploy after every change. As the previous lesson showed, this matters even more for NEXT_PUBLIC_ variables, which are baked into the build.

Every deployment is linked to its commit SHA and branch, so the dashboard always tells you which commit production is running. After a deploy, check the domain, HTTPS, logs and database connection, and only call it done once the smoke test passes.

A deployment on this kind of platform is immutable: once built, it never changes, and every push produces a brand-new one next to the old ones. That is what makes rollback cheap. Going back does not mean rebuilding old code; it means pointing your domain at a deployment that already exists and is known to work. Keep that in mind when you design releases, because a database change is the one thing that cannot be pointed back the same way.

Mental model: proof copies and the printed book
  1. A branch push makes a preview URL
  2. Previews only touch the test DB
  3. Merging to main ships production
  4. Failed smoke test means rollback

At any moment you should be able to say which commit production runs and which deployment you would return to.

General pattern: from branch to production

bash
git switch -c feature/<name>
git push -u origin feature/<name>   # -> preview deployment with its own URL

# open a pull request, review the preview URL, then merge into main

git switch main
git pull
# merged commits on main -> production deployment

Each feature lives on a branch, and pushing it creates a preview. Only after review and a merge into main does a production deployment happen. The production branch can be changed in the project settings.

Example: the first deploy of Myanmar Notes

Push the code to a remote repository, then import it as a new project in the Vercel dashboard. Menu names in the dashboard change over time, so the steps are written in general terms. Add the environment variables before the first deploy, or the build will often fail.

bash
git add .
git commit -m "Build Myanmar Notes"
git push origin main

# Vercel dashboard
# 1. New Project → Import repository
# 2. Add environment variables
# 3. Select Deploy
# 4. Run a smoke test on the production URL

Code breakdown

  1. Record a known versiongit commit -m "Build Myanmar Notes"

    Every deployment is tied to a commit, so write a clear message; in an incident you trace changes through this SHA. Before git add ., confirm files such as .env.local are listed in .gitignore.

  2. The push that triggers a deploygit push origin main

    Once the project is connected, every push to main starts a new production deployment. Pushes to any other branch create preview deployments.

  3. One-time project setup# 1. New Project → Import repository

    When importing, check that the framework preset is Next.js and the root directory is right. You do this once per project.

  4. Variables before the first build

    In step 2, add variables such as DATABASE_URL and AUTH_SECRET per environment. The build may need them while rendering static pages, and adding them later means redeploying.

  5. Done means verified

    The last step is a smoke test on the production URL. A successful build only proves the code compiled; it says nothing about whether login, the database and images work.

You should see
You end up with an HTTPS production URL and a preview deployment workflow for every commit.

Guarding production data from previews

Splitting variables correctly in the dashboard is the first line of defence. As a second line, the code can check itself at startup. Vercel provides a system variable, VERCEL_ENV, set to production, preview or development, so a non-production deployment that tries to use the production database host can be stopped immediately.

lib/db-guard.ts
type Env = Record<string, string | undefined>;
const PROD_DB_HOST = "prod-db.internal";

export function checkDatabaseTarget(env: Env): string {
  const target = env.VERCEL_ENV ?? "development";
  const url = new URL(env.DATABASE_URL ?? "postgres://localhost/notes");
  if (target !== "production" && url.hostname === PROD_DB_HOST) {
    throw new Error(`${target} deployment must not use the production database`);
  }
  return `${target} -> ${url.hostname}`;
}

for (const env of [
  { VERCEL_ENV: "production", DATABASE_URL: "postgres://app@prod-db.internal/notes" },
  { VERCEL_ENV: "preview", DATABASE_URL: "postgres://app@test-db.internal/notes" },
  { VERCEL_ENV: "preview", DATABASE_URL: "postgres://app@prod-db.internal/notes" },
]) {
  try {
    console.log("ok   ", checkDatabaseTarget(env));
  } catch (err) {
    console.log("STOP ", (err as Error).message);
  }
}

Domains, the CLI and rollback

  • Custom domain: add the domain in the project settings and create the DNS records the dashboard shows at your registrar. The platform issues the HTTPS certificate.
  • Function region: run server code in a region close to your database. If the database is in Singapore and the functions run in the United States, every query crosses the planet.
  • CLI: the vercel command deploys a preview from the terminal, and vercel --prod deploys to production. vercel env pull downloads development variables into a local file.
  • Rollback: the dashboard can put a previous production deployment back in place without rebuilding. Check the current docs for the feature's exact name and any plan limits.

In real projects

In real projects

On many teams a bot posts the preview URL as a comment on every pull request. Designers, product managers and QA can open the real feature in a browser and give feedback without reading code. E2E tests run against that preview URL too, and a failure blocks the merge.

Teams arrange preview databases in different ways: one staging database shared by all previews, or a provider that can create a separate database branch for each Git branch. On the production side, CI runs a smoke-test script after every deploy and the team watches the error rate for about ten minutes. If something looks wrong, they roll back first and investigate the cause calmly afterwards.

Common mistakes

Common mistakes

  • Connecting preview deployments to the production database and production secrets. Unreviewed code gets permission to change or delete real users' data.
  • Declaring victory when the build turns "Ready" without trying a user flow. A wrong database connection string, or an OAuth callback URL that does not include the new domain yet, leaves the build untouched but breaks login.
  • Changing a variable in the dashboard without redeploying. The old deployment keeps running with the old value, and time is lost on "I fixed it but it still doesn't work".
  • Building a monorepo from the repository root without setting the root directory. The build cannot find the Next.js app and fails, or worse, builds the wrong package.

Mini challenge

Try it yourself: a post-deploy smoke test

Write a smoke-test script that takes a deployment URL and checks the status code and text of the key routes. If any check fails, tell the team to roll back. So it runs anywhere, use a small stand-in server built with node:http instead of a real deployment.

  • Each check has a path, an expected status and an optional contains text
  • Signed out, /dashboard must answer with a 307 redirect, so use redirect: "manual" in fetch
  • Print one PASS or FAIL line per check
  • Finish with the number of failures and whether to roll back
scripts/smoke.ts
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";

type Check = { path: string; status: number; contains?: string };

const CHECKS: Check[] = [
  // TODO: "/", "/notes", "/dashboard" (signed out), "/api/health", a missing note
];

export async function smoke(baseUrl: string): Promise<boolean> {
  // TODO: fetch each path without following redirects
  // TODO: compare status and body, print PASS/FAIL per check
  // TODO: print a final verdict and return true only if everything passed
  return false;
}

// TODO: a stand-in server with createServer(...) where /api/health is broken,
// listen on port 0, run smoke() against it, then close the server

Expected: PASS for /, /notes, /dashboard and the missing-note route, "FAIL /api/health -> 500" for the health check the stand-in server breaks on purpose, and finally "1 check(s) failed: roll back".

Show hint

Build each full URL with new URL(check.path, baseUrl). listen(0, ...) asks the OS for a free port, which you read back from server.address(). Call server.close() at the end so the process can exit.

Show solution
scripts/smoke.ts
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";

// Run after every deploy against the deployment URL
type Check = { path: string; status: number; contains?: string };

const CHECKS: Check[] = [
  { path: "/", status: 200, contains: "Myanmar Notes" },
  { path: "/notes", status: 200 },
  { path: "/dashboard", status: 307 },
  { path: "/api/health", status: 200, contains: '"status":"ok"' },
  { path: "/notes/does-not-exist", status: 404 },
];

export async function smoke(baseUrl: string): Promise<boolean> {
  let failed = 0;
  for (const check of CHECKS) {
    const res = await fetch(new URL(check.path, baseUrl), { redirect: "manual" });
    const body = await res.text();
    const okStatus = res.status === check.status;
    const okBody = !check.contains || body.includes(check.contains);
    if (!okStatus || !okBody) failed++;
    const mark = okStatus && okBody ? "PASS" : "FAIL";
    const why = okStatus && !okBody ? ` (missing "${check.contains}")` : "";
    console.log(`${mark} ${check.path} -> ${res.status}${why}`);
  }
  const verdict = failed === 0 ? "smoke test passed" : `${failed} check(s) failed`;
  console.log(failed === 0 ? verdict : `${verdict}: roll back`);
  return failed === 0;
}

// Demo: a stand-in for the deployed app, so this file runs anywhere.
const fakeApp = createServer((req, res) => {
  const routes: Record<string, [number, string]> = {
    "/": [200, "<h1>Myanmar Notes</h1>"],
    "/notes": [200, "<ul></ul>"],
    "/api/health": [500, '{"status":"db down"}'],
  };
  if (req.url === "/dashboard") {
    res.writeHead(307, { location: "/login" }).end();
    return;
  }
  const [status, body] = routes[req.url ?? ""] ?? [404, "Not found"];
  res.writeHead(status).end(body);
});

fakeApp.listen(0, async () => {
  const { port } = fakeApp.address() as AddressInfo;
  await smoke(`http://127.0.0.1:${port}`);
  fakeApp.close();
});

Quick quiz 1 / 3

With the project connected, you push the feature/tags branch. What happens?

Quick quiz 2 / 3

You changed production's AUTH_SECRET in the dashboard. What must happen before the live site uses the new value?

Quick quiz 3 / 3

What is the best way to stop preview deployments from touching production data?

What to remember

  • Each branch push creates a preview deployment; merging into the production branch creates a production deployment
  • Give DATABASE_URL and secrets different values for Production, Preview and Development
  • Redeploy after changing variables, and trace every deployment by its commit SHA
  • A green build is not the finish; if the smoke test fails, put the previous deployment back

Next.js — Deploying — Next.js

Next.js — Deploying — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Production Deployment to Vercel | Thuta Learning