Databases and Deployment · Lesson 23 of 24
Environment Variables and Deploying Next.js
An app is only useful once it's online. Next.js runs almost anywhere: on Vercel (made by the same team), on any server that runs Node.js, in a Docker container, or as plain static files. Before choosing, you need to understand environment variables – how secrets and settings get into your app in each environment.
In this lesson
.envfiles and which one winsNEXT_PUBLIC_variables are fixed at build time- Deploying to Vercel, a Node server, Docker or static hosting
- A production checklist
.env files
# .env
API_URL=https://api.example.com
GREETING=Hello from .env
# .env.production
API_URL=https://api.learnfrenzy.com
# .env.local
GREETING=Hello from .env.local
// app/page.tsx
export default function Home() {
return (
<ul>
<li>API_URL = {process.env.API_URL}</li>
<li>GREETING = {process.env.GREETING}</li>
<li>NODE_ENV = {process.env.NODE_ENV}</li>
</ul>
);
}
• API_URL = https://api.learnfrenzy.com • GREETING = Hello from .env.local • NODE_ENV = production
| File | Loaded when | Commit to git? |
|---|---|---|
.env | always | yes – non-secret defaults |
.env.development / .env.production | next dev / next build + start | yes – non-secret, per environment |
.env.local | always, except in tests | no – secrets and personal overrides |
.env.production.local | production only | no |
The more specific file wins: .env.local beat .env for GREETING, and .env.production beat .env for API_URL in this production build. Real environment variables set on the server or hosting platform override all files. create-next-app adds .env* to .gitignore – keep secrets out of git.
NEXT_PUBLIC_ values are baked in at build time
Variables starting with NEXT_PUBLIC_ are copied into the JavaScript bundle when you run next build. Changing them on the server later has no effect until you rebuild, and anyone can read them – so never put secrets there. Server-only variables are read when the code runs, so they can differ per environment without a rebuild (for pages rendered at request time).
Deploy to Vercel
- Push your project to GitHub, GitLab or Bitbucket.
- Import the repository at vercel.com; it detects Next.js automatically.
- Add your environment variables in the project settings (separately for Production and Preview).
- Every push to the main branch deploys to production; every pull request gets its own preview URL.
Vercel runs Server Components and Actions as serverless functions, serves static files from a global CDN, and supports caching, streaming and image optimisation without configuration.
Self-hosting on a Node.js server
npm ci
npm run build
npm run start # serves on port 3000 – put Nginx or a load balancer in front
Everything works when self-hosted: caching, streaming, Server Actions, Proxy and image optimisation. Run it under a process manager (systemd, PM2) or in a container. With several instances, share the cache (cacheHandlers) and set the same NEXT_SERVER_ACTIONS_ENCRYPTION_KEY on each.
Docker with standalone output
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone", // copies only the files needed to run into .next/standalone
cacheComponents: true,
};
export default nextConfig;
# Dockerfile
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]
The standalone output contains a minimal server.js and only the dependencies your app uses, which makes images small. Run it anywhere that runs containers: Google Cloud Run, AWS, Azure, Fly.io, Railway, Render or your own VM.
Static export
With output: "export", next build writes plain HTML, CSS and JS to an out/ folder you can upload to any static host (S3, GitHub Pages, Netlify). You lose everything that needs a server: request-time rendering, Server Actions, Route Handlers other than static GET, Proxy, and the default image optimiser. It suits documentation, blogs and marketing sites.
Production checklist
npm run buildpasses locally with no type or lint errors; check the route table – are the pages you expect static?- All environment variables are set on the host; no secrets in
NEXT_PUBLIC_variables or in git. - Metadata,
sitemap.xml,robots.txtand a custom 404 page are in place. - Error monitoring (Sentry or similar, via
instrumentation.ts) and analytics are configured. - Core Web Vitals are healthy: images via
next/image, fonts vianext/font, slow data behindSuspense. - Every Server Action and Route Handler checks authentication and validates input.
Practice
Try it yourself
Show a banner only when
NEXT_PUBLIC_STAGEisstaging, set in.env.production.Show solution
# .env.production NEXT_PUBLIC_STAGE=staging// app/page.tsx export default function Home() { return ( <main> {process.env.NEXT_PUBLIC_STAGE === "staging" && <p role="status">⚠ Staging site – data may be reset</p>} <h1>LearnFrenzy</h1> </main> ); }⚠ Staging site – data may be reset LearnFrenzy
Quick check
Which .env file should hold secrets on your machine?
.env.local (never committed).
When is a NEXT_PUBLIC_ variable's value fixed?
At build time – it's inlined into the bundle.
What does output: "standalone" give you?
A minimal server.js with only the needed files – ideal for Docker.
Summary
- .env files load in order of specificity; .env.local holds secrets and is never committed.
- NEXT_PUBLIC_ variables are public and fixed at build time.
- Deploy to Vercel, run next start on a Node server, use standalone output for Docker, or export static files.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.