Deploying a Next.js App to Vercel

By Published 7 min read

Deploying a Next.js App to Vercel

Introduction:

So far in this course we have built pages, routes, API routes, ISR and middleware, but everything has run on localhost. In this lesson we will put a Next.js app on the internet.

The easiest place to deploy Next.js is Vercel, the company that created Next.js. Vercel understands every Next.js feature without any configuration: static pages are served from a global CDN, API routes become serverless functions, ISR pages are regenerated in the background, and middleware runs before each request. Best of all, once your GitHub repository is connected, every git push deploys your site automatically.

What You Need

  • A Next.js project that runs with npm run dev.
  • The project pushed to a repository on GitHub (GitLab and Bitbucket work too).
  • A free Vercel account. Sign up at vercel.com with your GitHub account so Vercel can see your repositories.

Step 1: Make Sure the Project Builds

Vercel runs the same build command you can run on your own computer. If the build fails locally, it will fail on Vercel too, so always check first:

npm run build

If the build succeeds, Next.js prints a table of your routes. The symbol in front of each route tells you how Vercel will serve it:

Route (pages)    Revalidate  Expire
┌ ● /                    1m      1y
├ ○ /404
└ ƒ /api/health

○  (Static)   prerendered as static content
●  (SSG)      prerendered as static HTML (uses getStaticProps)
ƒ  (Dynamic)  server-rendered on demand

Here / is a static page that is regenerated at most once a minute (ISR with revalidate: 60), /404 is plain static HTML, and /api/health is an API route that runs on demand as a serverless function.

Step 2: Push the Project to GitHub

If your project is not on GitHub yet, create an empty repository on github.com and push your code:

git init
git add .
git commit -m "First commit"
git branch -M main
git remote add origin https://github.com/your-username/my-next-app.git
git push -u origin main

Make sure .env.local and node_modules are listed in .gitignore. Secrets such as database passwords must never be committed; we will give them to Vercel separately in Step 4.

Step 3: Import the Project on Vercel

  1. Open your Vercel dashboard and click Add New… and then Project.
  2. Find your repository in the list and click Import.
  3. Vercel detects that it is a Next.js project and fills in the settings for you: the framework preset is Next.js, the build command is next build, and the output is handled automatically. You normally do not need to change anything.
  4. If your Next.js app lives in a sub-folder of the repository (for example web/), set the Root Directory to that folder.
  5. Click Deploy.

After a minute or two you will see a preview of your site and a URL such as my-next-app.vercel.app. Your app is live.

Step 4: Environment Variables

Most real apps need settings that should not be in the code: database URLs, API keys, or the site’s name. Locally you keep them in .env.local. On Vercel you add them in the project’s Settings, under Environment Variables.

For each variable you choose which environments get it:

  • Production: your live site.
  • Preview: deployments of other branches and pull requests.
  • Development: used when you run vercel dev or pull the variables to your computer.

There are two kinds of variables in Next.js, and the difference matters:

  • Variables that start with NEXT_PUBLIC_ are copied into the JavaScript sent to the browser when the app is built. Use them only for values that are safe for anyone to see, such as the site name or a public analytics ID.
  • All other variables are available only on the server: in getStaticProps, getServerSideProps, API routes and middleware. Database passwords and secret keys go here.
// pages/index.js
export async function getStaticProps() {
  return {
    props: {
      siteName: process.env.NEXT_PUBLIC_SITE_NAME || "My Next.js App",
      builtAt: new Date().toISOString(),
    },
    revalidate: 60,
  };
}

export default function Home({ siteName, builtAt }) {
  return (
    <main>
      <h1>{siteName}</h1>
      <p>Page generated at {builtAt}</p>
    </main>
  );
}

Vercel also adds its own system environment variables to every deployment. Two useful ones are VERCEL_ENV (production, preview or development) and VERCEL_GIT_COMMIT_SHA (the commit that was deployed). Here is a small health-check API route that uses them:

// pages/api/health.js
export default function handler(req, res) {
  res.status(200).json({
    ok: true,
    env: process.env.VERCEL_ENV || "local",
    commit: process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7) || null,
    hasDbUrl: Boolean(process.env.DATABASE_URL),
  });
}

Running it locally with a DATABASE_URL set returns:

{"ok":true,"env":"local","commit":null,"hasDbUrl":true}

On Vercel, env shows production or preview and commit shows the short commit ID, so you can always check which version is live.

Important: changing an environment variable does not change deployments that already exist. After you add or edit a variable, redeploy (from the Deployments tab, or by pushing a new commit) so the new value is used. This is especially true for NEXT_PUBLIC_ variables, which are fixed at build time.

Step 5: Automatic Deployments and Previews

Once the repository is connected, you never have to deploy by hand again:

  • Push to main (the production branch) and Vercel builds and publishes a new production deployment on your main domain.
  • Push to any other branch or open a pull request and Vercel builds a preview deployment with its own unique URL. Vercel also posts the preview link on the pull request in GitHub.

Previews are one of Vercel’s best features. You can test a new page, share the link with a friend or a client, and only merge into main when everything looks right. A typical workflow looks like this:

git checkout -b new-pricing-page
# ...make your changes...
git add .
git commit -m "Add pricing page"
git push -u origin new-pricing-page
# Vercel builds a preview URL for this branch
# Open a pull request, check the preview, then merge into main
# Vercel deploys main to production

Step 6: Add a Custom Domain

A .vercel.app address is fine for testing, but a real site needs its own domain.

  1. In your project, open Settings and then Domains.
  2. Type your domain, for example example.com, and click Add. Vercel will suggest adding www.example.com too and redirecting one to the other.
  3. Vercel shows the DNS records you need. Usually this is an A record for the root domain and a CNAME record for www. Log in to the company where you bought the domain and add exactly the values Vercel shows.
  4. DNS changes can take from a few minutes to a few hours to spread. When they do, Vercel marks the domain as valid and issues a free HTTPS certificate automatically.

If you bought the domain on Vercel itself, there is nothing to configure: it works straight away.

Step 7: Deploying from the Command Line

You can also deploy without GitHub using the Vercel CLI. This is handy for quick experiments or for pulling your environment variables to your computer.

npm install -g vercel

vercel login             # sign in once
vercel                   # link the folder to a project and create a preview deployment
vercel --prod            # deploy to production
vercel env pull .env.local   # download the Development environment variables

The first time you run vercel in a folder it asks a few questions (which account, which project name) and then remembers the answers in a .vercel folder. Add .vercel to .gitignore.

Step 8: Rolling Back a Bad Deployment

Sooner or later a deployment will break something. Because every deployment on Vercel is kept, going back is quick: open the Deployments tab, find the last deployment that worked, open its menu and choose Instant Rollback (or Promote to Production). Your domain switches back to that version in seconds, without a new build. Then fix the bug calmly and push again.

Common Problems and Fixes

1. “Module not found” on Vercel but it works locally:

Windows and macOS ignore upper and lower case in file names, but Vercel builds on Linux, which does not. If the file is components/Navbar.js and you import ../components/navbar, it works on your laptop and fails on Vercel. Make the import match the file name exactly.

2. A variable is undefined in production:

Check that it was added for the Production environment, that its name is spelled the same, and that you redeployed after adding it. If the browser needs it, the name must start with NEXT_PUBLIC_.

3. The build fails with type or lint errors:

Run npm run build locally, fix the errors it shows, and push again. The build log on Vercel (open the failed deployment) shows the same messages.

4. A different Node.js version:

If your project needs a specific Node.js version, set it in Settings, under General, or add an engines field to package.json:

{
  "engines": {
    "node": "22.x"
  }
}

What Happens to Each Next.js Feature on Vercel

  • Static pages and getStaticProps: built once and served from Vercel’s global CDN, close to your visitors.
  • ISR (revalidate): the cached page is served instantly, and Vercel regenerates it in the background when it is older than the revalidate time.
  • getServerSideProps and API routes: run as Vercel Functions (serverless functions) on every request.
  • Middleware: runs before the request reaches your pages, so redirects and authentication checks happen early.
  • next/image: images are resized and optimized automatically.

Conclusion:

Deploying Next.js to Vercel takes only a few steps: make sure npm run build works, push the project to GitHub, import it on Vercel, and add your environment variables. From then on every push to main goes live automatically, every branch gets its own preview URL, and a bad release can be rolled back in seconds. Add a custom domain and your app is ready for real users.

In the next lesson we will look at image optimization with next/image, which makes your pages load faster on every device.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume