🌍 NextJS · subject

NextJS Deployment and Scaling Syllabus

The Deployment and Scaling syllabus for NextJS in full: 3 chapters and 9 topics, every one listed below, plus 51 Deployment and Scaling flashcards with answers.

3Chapters
9Topics
51Flashcards

Deployment and Scaling syllabus: all 3 chapters

Expand any chapter to see its topics and sub-topics.

  1. Vercel Deployment

    3 topics
    • Setting Up Vercel
    • Deploying a Next.js App
    • Environment Variables
  2. Custom Server

    3 topics
    • When to Use a Custom Server
    • Setting Up a Custom Server
    • Handling Routes in Custom Server
  3. Scaling and Load Balancing

    3 topics
    • Horizontal Scaling
    • Load Balancers
    • Monitoring and Logging

NextJS Deployment and Scaling flashcards — 51 questions with answers

  1. What is Vercel and why is it the recommended platform for deploying Next.js apps?

    Vercel is the cloud platform built by the creators of Next.js. It is recommended because it offers zero-configuration deployment, native support for Next.js features (SSR, ISR, Server Components, Edge/Serverless Functions, Image Optimization), a global edge network/CDN, and automatic Git-based CI/CD.

  2. What are the basic steps to set up a project on Vercel from a Git repository?

    1) Create a Vercel account and connect your Git provider (GitHub/GitLab/Bitbucket). 2) Click 'Add New Project' and import the repository. 3) Vercel auto-detects Next.js and sets the framework preset. 4) Configure environment variables if needed. 5) Click 'Deploy'.

  3. What is the Vercel CLI command to deploy the current project directory?

    Run `vercel` to create a preview deployment, or `vercel --prod` to deploy to production. First-time use runs `vercel login` and links the local folder to a Vercel project.

  4. On Vercel, what is the difference between a Preview deployment and a Production deployment?

    A Preview deployment is created for every push to a non-production branch (or PR) and gets a unique preview URL for testing. A Production deployment is created from the production branch (default `main`) and is served on the project's production domain.

  5. What build and output settings does Vercel use by default for a Next.js app?

    Build command: `next build`; Output: Vercel handles the `.next` output automatically via its Next.js build adapter; Install command: `npm install` (or detected package manager); Development command: `next dev`. These are auto-detected from the framework preset.

  6. What happens automatically when you push a commit to the production branch of a Vercel-linked repo?

    Vercel triggers a new build and production deployment automatically (Git-based CI/CD). On success it atomically swaps the production alias to the new deployment; the previous deployment remains accessible via its immutable URL for instant rollback.

  7. What is an environment variable and why is it used in a Next.js deployment?

    An environment variable is a key-value pair set outside the source code to configure the app per environment (development, preview, production). It is used to store secrets (API keys, database URLs) and environment-specific config without hardcoding them in the codebase.

  8. In Next.js, what determines whether an environment variable is exposed to the browser?

    Only variables prefixed with `NEXT_PUBLIC_` are inlined into the client bundle and exposed to the browser. All other environment variables are available only on the server (during build/runtime) and are never sent to the client.

  9. How does Next.js load environment variables from files, and in what precedence order?

    Next.js loads from `.env` files automatically. Precedence (highest first): `.env.$(NODE_ENV).local` > `.env.local` (not loaded in test) > `.env.$(NODE_ENV)` > `.env`. Actual process environment variables always override file values.

  10. Why should `.env.local` be added to `.gitignore`?

    `.env.local` typically holds secrets (API keys, database credentials) specific to a developer's machine. Committing it would leak secrets into version control, so it must be excluded from Git.

  11. How do you access an environment variable named DATABASE_URL in Next.js server code?

    Reference it via `process.env.DATABASE_URL`. On the server this reads the runtime value; because it lacks the `NEXT_PUBLIC_` prefix it is not exposed to the client.

  12. When are `NEXT_PUBLIC_` environment variables embedded into the Next.js bundle?

    At build time. Their values are statically inlined into the JavaScript bundle during `next build`, so changing them requires a rebuild/redeploy rather than just a restart.

  13. How do you configure environment variables for a deployed project on Vercel?

    In the Vercel dashboard under Project Settings > Environment Variables, add key-value pairs and select the target environments (Production, Preview, Development). You can also use `vercel env add` from the CLI. A redeploy applies the changes.

  14. What is a custom server in Next.js?

    A custom server is a Node.js server (e.g. using Express, Koa, or the built-in `http` module) that you write yourself to programmatically handle requests and hand them off to Next.js's request handler, replacing the default `next start` server.

  15. List common reasons you WOULD need a custom server in Next.js.

    Integrating Next.js into an existing Node/Express app, implementing fully custom server-side routing/rewrites not expressible via config, running a WebSocket/Socket.io server on the same process, custom server-level middleware/proxying, or specialized caching logic.

  16. Why does using a custom server disable deployment on Vercel and similar serverless platforms?

    A custom server requires a single long-running Node process, which is incompatible with serverless/automatic scaling. Platforms like Vercel deploy Next.js as serverless functions and cannot run a persistent custom server, so features like ISR and automatic optimizations may be lost.

  17. What is the recommended alternative to a custom server for most routing/logic needs in modern Next.js?

    Use built-in features instead: Middleware (`middleware.ts`), Route Handlers / API Routes, `rewrites`/`redirects` in `next.config.js`, and the App Router. These avoid opting out of serverless deployment and preserve automatic optimizations.

  18. In a custom server, which Next.js function creates the app instance and which produces the request handler?

    `next({ dev })` creates the Next.js app instance; calling `app.getRequestHandler()` returns the handler function used to process incoming HTTP requests. You must also `await app.prepare()` before serving.

  19. Write the minimal structure of a Next.js custom server using the built-in http module.

    const next = require('next'); const { createServer } = require('http'); const app = next({ dev: process.env.NODE_ENV !== 'production' }); const handle = app.getRequestHandler(); app.prepare().then(() => { createServer((req, res) => handle(req, res)).listen(3000); });

  20. In a custom server, what is the purpose of calling `await app.prepare()`?

    `app.prepare()` initializes the Next.js app (compiles pages in dev, loads the build manifest in prod) and must resolve before the server starts handling requests, ensuring Next.js is ready to render.

Show the other 31 Deployment and Scaling flashcards
  1. When running a custom server, why must you set the script to run `node server.js` instead of `next start`?

    Because the custom server file (`server.js`) IS the server entry point. `next start` launches Next.js's default server and would bypass your custom logic, so `package.json` scripts use `node server.js` (and `NODE_ENV=production node server.js` in prod).

  2. In an Express-based custom server, how do you route a specific URL to a custom page render while letting Next.js handle everything else?

    Define specific routes first (e.g. `server.get('/post/:id', (req, res) => app.render(req, res, '/post', { id: req.params.id }))`), then add a catch-all `server.all('*', (req, res) => handle(req, res))` to delegate all remaining requests to Next.js.

  3. What is the difference between `app.render()` and the request handler `handle()` in a custom server?

    `app.render(req, res, pagePath, query)` explicitly renders a specific Next.js page with custom query params. `handle(req, res)` uses Next.js's built-in routing to match the URL to the appropriate page/asset automatically.

  4. Why must a custom server parse the request URL (e.g. with Node's `url.parse`) before passing it to Next.js?

    Next.js's request handler expects a parsed URL object containing the pathname and query so it can correctly match routes and serve assets. Passing `parse(req.url, true)` provides that parsed query information (`handle(req, res, parsedUrl)`).

  5. In a custom server, how would you serve static Next.js assets from `/_next`?

    Requests to `/_next/*` should be delegated to Next.js's handler (e.g. `server.all('/_next/*', (req, res) => handle(req, res))`), because Next.js manages its own build assets and static files under that path.

  6. Define horizontal scaling.

    Horizontal scaling (scaling out) is adding more machines/instances to distribute load across many nodes running the same application, rather than increasing the power of a single machine.

  7. Contrast horizontal scaling with vertical scaling.

    Vertical scaling (scaling up) increases the resources (CPU, RAM) of a single server and has a hardware ceiling plus a single point of failure. Horizontal scaling (scaling out) adds more identical instances, offering near-limitless growth, fault tolerance, and requiring a load balancer.

  8. What application property is required to make horizontal scaling effective, and why?

    Statelessness. Each instance must not store session/user state locally so any request can be served by any instance. Shared state must live in external stores (database, Redis, etc.), enabling instances to be added/removed freely.

  9. Why are Next.js serverless deployments (e.g. on Vercel) naturally horizontally scalable?

    Each request is handled by a stateless serverless function instance that the platform spins up on demand and runs many copies of in parallel across regions, so scaling out to handle load is automatic and requires no manual instance management.

  10. When self-hosting a custom Next.js server for horizontal scaling, what tool is commonly used to run multiple Node processes on one machine?

    A process manager like PM2 (in cluster mode) or Node's built-in `cluster` module, which forks one worker per CPU core to utilize all cores, often combined with multiple machines behind a load balancer.

  11. What is a load balancer?

    A load balancer is a component (hardware or software) that sits in front of multiple server instances and distributes incoming network traffic across them to optimize resource use, maximize throughput, minimize latency, and provide fault tolerance.

  12. Name common load balancing algorithms and briefly describe each.

    Round Robin (requests cycled sequentially across servers); Least Connections (route to the server with fewest active connections); IP Hash (client IP hashed to a consistent server); Weighted Round Robin (servers get traffic proportional to assigned weights based on capacity).

  13. What is sticky session (session affinity) in a load balancer, and when is it needed?

    Sticky sessions bind a client to the same backend instance for the duration of its session (usually via a cookie or IP hash). It is needed when servers store per-user state locally, but it is best avoided by making the app stateless.

  14. What is a health check in the context of a load balancer?

    A health check is a periodic probe (e.g. an HTTP request to `/health`) the load balancer sends to each backend instance. Instances that fail are marked unhealthy and removed from rotation until they pass again, preventing traffic to broken nodes.

  15. At which OSI layers do load balancers typically operate, and what's the difference?

    Layer 4 (transport) load balancers route based on IP address and TCP/UDP ports without inspecting content. Layer 7 (application) load balancers inspect HTTP data (URL path, headers, cookies) enabling content-based routing, SSL termination, and more intelligent distribution.

  16. What is SSL/TLS termination at a load balancer?

    SSL/TLS termination is when the load balancer decrypts incoming HTTPS traffic and forwards plain HTTP to backend instances, offloading encryption work from the app servers and centralizing certificate management.

  17. How does a CDN complement horizontal scaling for a Next.js app?

    A CDN caches static assets and pre-rendered/ISR pages at edge locations close to users, serving them without hitting origin servers. This reduces origin load and latency, letting backend instances handle only dynamic requests.

  18. What is monitoring in application operations?

    Monitoring is the continuous collection, aggregation, and analysis of metrics (response time, error rate, CPU, memory, throughput) about a system's health and performance to detect problems and trigger alerts.

  19. What is logging, and how does it differ from monitoring?

    Logging records discrete, timestamped event records (requests, errors, custom messages) for detailed inspection and debugging. Monitoring aggregates numeric metrics over time for health/trend analysis and alerting. Logs answer 'what happened'; metrics answer 'how is it performing'.

  20. What are the three pillars of observability?

    Metrics (numeric measurements over time), Logs (discrete timestamped event records), and Traces (end-to-end request paths across services/functions). Together they enable understanding a system's internal state from its outputs.

  21. What built-in tools does Vercel provide for monitoring a Next.js deployment?

    Vercel provides runtime Logs (function/build logs), Analytics (traffic and audience insights), Speed Insights (real-user Core Web Vitals), and Observability/Monitoring dashboards for metrics like function invocations, errors, and latency.

  22. What are Core Web Vitals, and which three metrics do they include?

    Core Web Vitals are Google's user-experience performance metrics: LCP (Largest Contentful Paint, loading), INP (Interaction to Next Paint, responsiveness — replaced FID), and CLS (Cumulative Layout Shift, visual stability).

  23. What are the 'good' target thresholds for LCP, INP, and CLS?

    LCP $\leq 2.5$ s, INP $\leq 200$ ms, and CLS $\leq 0.1$. These are the thresholds Google considers a good user experience (measured at the 75th percentile of page loads).

  24. How is Cumulative Layout Shift (CLS) conceptually calculated?

    CLS is the sum of individual layout shift scores, where each shift score is the product of the impact fraction and the distance fraction: $$\text{layout shift score} = \text{impact fraction} \times \text{distance fraction}$$ Lower is better; good is $\leq 0.1$.

  25. Give the formula for a service's availability in terms of MTBF and MTTR.

    $$\text{Availability} = \frac{\text{MTBF}}{\text{MTBF} + \text{MTTR}}$$ where MTBF is mean time between failures and MTTR is mean time to repair. Often expressed as a percentage (e.g. 99.9% uptime).

  26. How is error rate typically defined as a monitoring metric?

    $$\text{Error Rate} = \frac{\text{number of failed requests}}{\text{total number of requests}} \times 100\%$$ commonly the fraction of responses with 5xx (or 4xx+5xx) status codes over a time window.

  27. What does '99.9% availability' (three nines) allow as approximate downtime per year?

    About 8.77 hours per year. Downtime $= (1 - 0.999) \times 365 \times 24 \approx 8.76$ hours/year (roughly 43.8 minutes per month).

  28. What are the RED metrics used for monitoring request-driven services?

    Rate (requests per second), Errors (number/percentage of failed requests), and Duration (latency distribution of requests). RED gives a concise view of service health from the request perspective.

  29. What is structured logging and why is it preferred in production?

    Structured logging emits logs in a machine-parseable format (typically JSON) with consistent fields (timestamp, level, message, metadata). It is preferred because log aggregation tools can index, filter, search, and alert on the fields efficiently, unlike free-form text.

  30. Why is the 95th or 99th percentile (p95/p99) latency more useful than average latency for monitoring?

    Averages hide outliers and can mask a poor experience for a subset of users. p95/p99 reveal the tail latency — the slowest 5% or 1% of requests — reflecting the worst-case experience that averages obscure.

  31. Name common third-party monitoring/logging tools you might integrate with a self-hosted Next.js app.

    Sentry (error tracking), Datadog / New Relic (APM and metrics), Prometheus + Grafana (metrics collection and dashboards), the ELK/Elastic stack or Logtail/Better Stack (log aggregation), and OpenTelemetry for standardized traces/metrics/logs.

NextJS Deployment and Scaling FAQ

What is in the NextJS Deployment and Scaling syllabus?

NextJS Deployment and Scaling is split into 3 chapters: Vercel Deployment, Custom Server and Scaling and Load Balancing. Together they contain 9 topics.

How many chapters are in NextJS Deployment and Scaling?

3 chapters, containing 9 topics. The largest chapter is Vercel Deployment, with 3 topics.

Are there flashcards for NextJS Deployment and Scaling?

Yes — a 51-card Deployment and Scaling deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.