1. Building for Production

When you run npm run dev, Next.js compiles your app on-demand for fast iteration. Production is different โ€” Next.js pre-renders everything it can, tree-shakes unused code, minifies JavaScript and CSS, and generates an optimised build artefact ready to serve millions of requests.

The build command is npm run build. Run it before every deployment.

terminal Build command

After the build completes, Next.js prints a route table showing exactly what it produced for each page:

$ npm run build โ€” output
โ–ฒ Next.js 14.2.0 Route (app) Size First Load JS โ”Œ โ—‹ / 2.1 kB 87.8 kB โ”œ โ—‹ /products 3.4 kB 89.1 kB โ”œ โ— /product/[id] 1.8 kB 87.5 kB โ”” โ—‹ /checkout 4.2 kB 89.9 kB โ—‹ (Static) โ— (Dynamic) โœ“ Compiled successfully in 8.3s
โ—‹

Static (โ—‹)

Pre-rendered at build time to HTML. Served instantly from a CDN. Zero server cost per request. Best for pages that don't change per-user: Home, Products listing, Checkout.

โ—

Dynamic (โ—)

Rendered on the server at request time. Used when the page depends on runtime data โ€” e.g. /product/[id] needs to fetch the right product based on the URL parameter.

First Load JS is the total JavaScript the browser must parse before the page is interactive. Next.js splits bundles per-route so users only download code for the page they're on โ€” not your entire app.
๐Ÿ›’
UrbanCart Example
Reading the build output

The UrbanCart homepage (/) and products listing (/products) are marked โ—‹ โ€” they're statically generated at build time. The product detail page (/product/[id]) is โ— โ€” it's dynamic because the product data depends on which id is in the URL. The Checkout page is static because its layout doesn't change per-user.

2. Environment Variables

Production apps need secrets โ€” API keys, database URLs, payment gateway credentials. You should never hard-code these values in your source code. Next.js has a structured system for managing them across different environments.

The .env files

.env.local Development environment (never commit to git)
.env.production Production environment (set in deployment dashboard or CI)

The NEXT_PUBLIC_ prefix

By default, environment variables are only available on the server. If you want a variable accessible in browser (client) code โ€” for example, a publishable API key that goes into a JavaScript SDK โ€” prefix it with NEXT_PUBLIC_.

๐Ÿ”’

Server-only (no prefix)

Available in Server Components, API Routes, getServerSideProps. Never sent to the browser. Use this for secrets: DATABASE_URL, STRIPE_SECRET_KEY.

๐ŸŒ

Client-exposed (NEXT_PUBLIC_)

Baked into the browser bundle at build time. Use for non-secret public values: NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY, NEXT_PUBLIC_API_URL.

app/checkout/page.tsx Using env vars in a component
Security rule: Always add .env.local to your .gitignore. Never commit real API keys to git โ€” even a private repo. On Vercel, set production secrets in the dashboard under Project Settings โ†’ Environment Variables.

3. Vercel Deployment

Vercel is the company that created Next.js, and their hosting platform is designed around it. Deploying is as close to zero-configuration as anything in web development gets.

Vercel Deployment Flow
git push
Push to GitHub/GitLab
โ†’
Vercel detects push
Auto-triggered build
โ†’
npm run build
Runs in Vercel CI
โ†’
Live on CDN
Preview or Production URL

Step-by-step first deploy

  1. Push your Next.js project to a GitHub repository.
  2. Go to vercel.com and sign in with GitHub.
  3. Click "Add New Project" and import your repository.
  4. Vercel auto-detects Next.js โ€” no build command configuration needed.
  5. Add your environment variables in the project settings.
  6. Click "Deploy". Your app is live in ~60 seconds.
๐Ÿ”

Preview URLs

Every pull request and every branch push gets its own preview URL like urbancart-git-feature-abc.vercel.app. Share with your team before merging.

๐ŸŒ

Production URL

Merging to main deploys to your production domain โ€” either the auto-generated urbancart.vercel.app or your custom domain like urbancart.com.

Vercel CLI alternative
npm install -g vercel # install once vercel # deploy from terminal (interactive setup) vercel --prod # deploy to production URL directly
Free tier: Vercel's Hobby plan is free for personal projects with generous limits โ€” 100 GB bandwidth, serverless functions, Edge Network CDN. UrbanCart's tutorial version runs comfortably on it.

4. Other Hosting Options

Vercel is the easiest choice, but it's not the only one. Depending on your project's needs โ€” a Postgres database, a longer-running Node process, cost constraints โ€” other platforms may suit you better.

Platform Best for Free tier Notes
Vercel Next.js, static sites, Edge Functions Yes Zero-config, made by Next.js team
Railway Node.js + Postgres, full-stack apps $5 credit Best when you need a managed database alongside your app
Render Node.js services, Postgres, cron jobs Yes (spins down) Free tier spins down after 15 min inactivity โ€” slow cold start
Self-hosted Full control, VPS, Docker Your server Run npm run build && npm start on any Node.js server
terminal Self-hosted with next start
When to choose Railway over Vercel: If UrbanCart needs a real Postgres database (not just a cloud API), Railway lets you run your Next.js app and a Postgres instance side by side, connected via an internal network. Vercel requires an external database service.

5. Performance Optimisation

Next.js ships built-in components that handle the most common performance mistakes automatically. Two you'll use in every project: next/image and next/font.

next/image โ€” Automatic image optimisation

A plain <img> tag serves whatever file you uploaded โ€” full-resolution JPEG, even to a user on mobile with a small screen. next/image fixes this automatically.

โŒ

Plain img tag (slow)

Serves full-size image to all devices. No lazy loading. Browser does extra work to resize. No WebP conversion.

โœ…

next/image (fast)

Resizes to viewport, converts to WebP, lazy-loads off-screen images, prevents layout shift with reserved space.

app/products/page.tsx Plain img vs next/image

next/font โ€” Zero layout shift fonts

Loading Google Fonts the traditional way (<link> in the head) causes a flash of unstyled text โ€” your fallback font renders, then swaps to the real font mid-page. next/font downloads the font at build time and inlines a CSS variable, eliminating the shift entirely.

app/layout.tsx next/font for zero layout shift

Bundle analysis

If your First Load JS is unexpectedly large, use the bundle analyser to see what's taking up space:

terminal + next.config.js Analyse bundle size

6. SEO with the Metadata API

Next.js 13+ introduces the Metadata API โ€” export a metadata object or a generateMetadata function from any page.tsx file and Next.js automatically injects the right <meta> tags into the <head>. No manual head management needed.

app/page.tsx Full metadata export for UrbanCart homepage
app/product/[id]/page.tsx Dynamic metadata per product
og:image matters: WhatsApp, LinkedIn, and Twitter all show a preview card when someone shares a URL. Without an og:image, the preview is blank. Set one for your homepage and product pages โ€” it directly affects click-through rates.

7. next.config.js

The next.config.js file in your project root controls Next.js behaviour: which external image domains are allowed, URL redirects, headers, and more.

next.config.js Image domains, redirects, and headers
Common mistake: Forgetting to add external image domains to remotePatterns. If you use next/image with a URL from Cloudinary or your CDN and the domain isn't listed, Next.js will throw an error and the image won't load.

8. Checking Lighthouse Scores

Lighthouse is Google's built-in tool for auditing web app quality. It scores your app across four dimensions and flags specific issues you can fix. Run it in Chrome DevTools โ†’ Lighthouse tab, or via the command line.

98
Performance
100
Accessibility
100
Best Practices
100
SEO

A well-optimised Next.js app with next/image, next/font, and proper metadata can hit near-perfect scores. The most common culprits that drag scores down:

๐Ÿ–ผ๏ธ

Unoptimised images

Using plain <img> instead of next/image. Fix by migrating all product images to the Image component.

๐Ÿ“ฆ

Large JS bundles

Importing heavy libraries (Lodash, Moment.js) that ship too much code. Use lighter alternatives or dynamic imports.

โ™ฟ

Missing alt text

Images without alt attributes fail accessibility. Always provide descriptive alt text for product images.

Run Lighthouse from the command line
npx lighthouse https://urbancart.com \ --output html \ --output-path ./lighthouse-report.html \ --chrome-flags="--headless" # Opens a full HTML report in your browser
Always test in production mode: Lighthouse scores in npm run dev are artificially low because development builds include extra debugging code. Always run Lighthouse against your deployed production URL or a npm run build && npm start local server.

Quiz

Question 1 of 5
What does the NEXT_PUBLIC_ prefix do for environment variables?
Question 2 of 5
What is the main benefit of using next/image over a regular img tag?
Question 3 of 5
What does npm run build do in a Next.js project?
Question 4 of 5
What platform is the easiest for deploying Next.js apps?
Question 5 of 5
What does a โ—‹ symbol mean in the Next.js build output?
0
/ 5
Great job!

You completed the Deployment & Production quiz.

Next Lesson

TypeScript Fundamentals โ†’
You've completed Next.js! Next up: Arc F โ€” TypeScript Bridge.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just shipped UrbanCart to production.
Now launch a career that's just as live.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’