Skip to content
Visual explainer 3h to learn 4 steps

Deploying with CI & preview environments

Deploy on every push with preview URLs, environment variables and checks.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 34 of 36

In short

Continuous deployment builds and ships your app on every push. Each pull request gets a preview URL and automated checks, and merging to main deploys to production.

Explained simply

Deploying means putting your app on a server so anyone can open it. In the old days that was a manual job with many steps. Today a platform like Vercel watches your Git repository and deploys automatically every time you push.

Every pull request gets its own preview deployment: a real, live copy of the site with your changes at its own URL. Teammates can click through it before anything reaches real users. When the pull request is merged into main, the platform builds and deploys to production.

Apps need settings like database addresses and API keys. These live in environment variables, set in the platform's dashboard, with different values for development, preview and production. They never go into your Git repository.

Continuous integration (CI) is the safety net. Before a change can be merged, automatic checks run: lint, type check, tests and a build. If any check fails, the merge button stays blocked.

Press Play on a diagram to walk through it one step at a time.

FlowFrom push to production
  1. 1
    Push branch

    Open a pull request

  2. 2
    CI checks

    Lint, type check, unit and E2E tests

  3. 3
    Preview deploy

    Unique URL to review the change

  4. 4
    Merge to main

    Only after checks pass and review

  5. 5
    Production deploy

    Same build steps, production env vars

MapOne repo, three environments
Your Git repository
  • Development
    • Your laptop, next dev
    • .env.local (not committed)
    • Local or dev database
  • Preview
    • Every branch and pull request
    • Unique URL per deployment
    • Test database, test API keys
  • Production
    • The main branch
    • Your real domain
    • Real database and secrets

In depth

Connecting a repository to Vercel

In the Vercel dashboard, choose to add a new project and import your GitHub, GitLab or Bitbucket repository. Vercel detects Next.js and fills in the build command and output settings, so the defaults usually work. The first deployment runs immediately and gives you a production URL on vercel.app; add your own domain later in the project's domain settings.

From then on, the Git integration does the work: a push to the production branch (main by default) creates a production deployment, and a push to any other branch creates a preview deployment. Vercel reports each deployment's status on the commit and comments on the pull request with the preview link. Every deployment is immutable and keeps its own URL, which is why Instant Rollback can switch production back to an earlier deployment in seconds without rebuilding. The Vercel CLI (npm i -g vercel) offers the same from the terminal: vercel link, vercel for a preview and vercel --prod.

FlowWhat one git push triggers
  1. 1
    git push

    Branch or main

  2. 2
    Webhook

    Git provider notifies Vercel

  3. 3
    Build

    npm install, next build with env vars

  4. 4
    Deploy

    Immutable deployment with its own URL

  5. 5
    Assign

    Preview URL, or production domain if main

Environment variables per environment

Vercel has three environments: Production, Preview and Development. Each variable can be set for any of them with different values, so production uses the real database while previews use a test database. You can even scope a preview value to one branch. Values are read at build time and at runtime by server code. After changing a variable, redeploy, because existing deployments keep the values they were built with.

Next.js adds one important rule. Variables are server-only by default. Only names starting with NEXT_PUBLIC_ are inlined into the JavaScript sent to browsers, and they are fixed when the app is built. So a secret must never have that prefix, and a public value changed after the build needs a new build. For local development, run vercel env pull .env.local to download development values; .env.local should be in .gitignore. Vercel also provides system variables such as VERCEL_ENV (production, preview or development) and VERCEL_GIT_COMMIT_SHA.

  • DATABASE_URL: server-only, different per environment
  • NEXT_PUBLIC_SITE_URL: visible to everyone, baked in at build
  • Validate required variables at start-up, for example with Zod
CompareServer-only vs public variables in Next.js
DATABASE_URL
  • Read by server code only
  • Never in the browser bundle
  • Use for secrets and keys
  • Read at runtime
NEXT_PUBLIC_API_URL
  • Inlined into client JavaScript
  • Anyone can read it
  • Only for public values
  • Fixed at build time

Preview deployments in a review workflow

A preview turns review from reading code into using the change. Product owners and designers can test on their own phones; reviewers can check that a bug is really fixed. Previews can be protected so only your team can open them, which matters when they show unreleased features. Automated tools can also use the URL: GitHub sends a deployment_status event when Vercel finishes, so a workflow can run Playwright or Lighthouse against the exact preview.

Previews need their own data. Never point them at the production database: one test that deletes rows would delete real user data. Use a separate preview database, or a database branch per pull request if your provider supports branching. Third-party integrations need the same care: use test-mode API keys for payments and email, and add preview domains to your auth provider's allowed callback URLs, or sign-in will fail on previews.

CI checks that guard the main branch

A typical CI job for a Next.js app runs on every pull request: install with npm ci (exact versions from package-lock.json), lint, type check with tsc --noEmit, run unit tests with vitest run, and run next build, which catches errors only visible in a production build. E2E tests can run in the same workflow or against the preview URL. Cache npm downloads with actions/setup-node's cache option to save time, and add a concurrency group with cancel-in-progress: true so a new push cancels the outdated run.

Checks only protect you if they are required. In GitHub, add a branch protection rule or ruleset on main that requires pull requests, requires the CI status checks to pass, and blocks direct pushes. Fast feedback matters: if CI takes 20 minutes, people start ignoring it. Run cheap checks first and in parallel jobs, and keep the full suite under about 10 minutes.

  • npm ci, not npm install, in CI
  • tsc --noEmit catches type errors that next dev may not stop on
  • concurrency group ci-${{ github.ref }} with cancel-in-progress: true

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Connect the repo to Vercel~45m
  2. 2
    Set environment variables per environment~45m
  3. 3
    Use preview deployments for pull requests~45m
  4. 4
    Run lint, type check and tests in CI~45m

Key points

  • Set environment variables separately for development, preview and production.
  • Never commit secrets; store them in the hosting platform's settings.
  • Make CI checks required so failing pull requests cannot merge.
  • Only variables prefixed NEXT_PUBLIC_ reach the browser in Next.js.

Key terms

Tap a card to flip it. 0/4 known

Examples

yaml
# .github/workflows/ci.yml
name: CI
on: [pull_request]
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }
      - run: npm ci
      - run: npm run lint
      - run: npx tsc --noEmit
      - run: npm test

Lint, type check and test on every pull request.

A fast, parallel CI workflow for pull requests

Step 1: the workflow runs on pull requests and on pushes to main. Step 2: concurrency cancels older runs for the same branch. Step 3: one job installs once with the npm cache and runs lint, type check, unit tests and build. Step 4: in GitHub settings, mark the check job as required on main so red pull requests cannot merge.

yaml
name: CI
on: { pull_request: {}, push: { branches: [main] } }
concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22, cache: npm }
      - run: npm ci
      - run: npm run lint && npx tsc --noEmit && npx vitest run
      - run: npm run build

Failing fast when an environment variable is missing

A preview deploy works but every page crashes, because DATABASE_URL was set only for Production. Step 1: describe the required variables with a Zod schema in one file. Step 2: parse process.env when the server starts, so a missing value fails with a clear message instead of a confusing error later. Step 3: import env from this file instead of reading process.env directly. Step 4: add the variable for Preview in Vercel and redeploy.

ts
// src/env.ts (server-only)
import { z } from 'zod';

const schema = z.object({
  DATABASE_URL: z.string().url(),
  AUTH_SECRET: z.string().min(32),
  NEXT_PUBLIC_SITE_URL: z.string().url(),
});

const parsed = schema.safeParse(process.env);
if (!parsed.success) {
  throw new Error('Invalid environment variables: ' + parsed.error.message);
}
export const env = parsed.data;

Quick reference

  • Push to main = production deploy; push to any other branch = preview deploy
  • vercel link, vercel (preview), vercel --prod, vercel env pull .env.local
  • Set env vars per environment; redeploy after changing them
  • Only NEXT_PUBLIC_ variables reach the browser, and they are fixed at build time
  • Never point previews at the production database
  • CI: npm ci, lint, tsc --noEmit, vitest run, next build
  • Make CI checks required on main with branch protection or a ruleset
  • Instant Rollback restores an earlier production deployment without rebuilding

Common mistakes

  • Using production database credentials in preview deployments.
  • Letting merges through when CI is red.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You change an environment variable in Vercel. When does a running deployment see the new value?

Question 2

2Which variable can safely hold a Stripe secret key in Next.js?

Question 3

3Why use npm ci instead of npm install in CI?

Question 4

4A failing CI check does not stop a pull request from being merged. What is missing?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    List the environment variables your app needs and decide, for each, which environments get it and whether it may be public.

  2. Exercise 2medium

    Add a concurrency rule and npm caching to an existing CI workflow, and explain what each does.

  3. Exercise 3hard

    Run Playwright against each Vercel preview after it finishes deploying, using the preview URL as the base URL.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is Vercel free for personal projects?
Vercel has a free Hobby plan meant for personal, non-commercial projects, with usage limits. Team and commercial use needs a paid plan, so check the current pricing page before you launch a business on it.
Can I deploy Next.js somewhere other than Vercel?
Yes. Next.js runs anywhere Node.js runs (next build then next start), in a Docker container, or on platforms such as Netlify, AWS Amplify and Cloudflare with adapters. Static exports can go on any static host.
Why does my app work locally but fail on Vercel?
The most common causes are a missing environment variable for that environment, a file name whose letter case differs from the import (Linux is case-sensitive), and code that only works with next dev. Read the build logs and run next build locally.
What is the difference between CI and CD?
Continuous integration runs automatic checks on every change. Continuous deployment goes one step further and releases each change that passes those checks to production automatically.

Go deeper

ShareXLinkedInWhatsApp