Images, Environment Variables and Config
A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.
What you will be able to do
#- Configure next/image correctly for local and remote sources including the Next.js 16 images changes.
- Predict exactly which environment variables reach the client bundle and when their values are frozen.
- Use next.config and the separate viewport export without reaching for removed options.
Overview
#The image pipeline you get for free
next/image wraps every image in an optimization pipeline: it serves appropriately sized files in modern formats, lazy-loads by default, and prevents layout shift when you give it intrinsic dimensions. Two props cover most real usage. priority tells the framework to preload the image because it is the Largest Contentful Paint element; Next.js 16 deprecates priority in favor of the preload prop. fill plus sizes handles responsive containers: the image stretches to its positioned parent and sizes tells the browser which slot width to fetch at each viewport.
import Image from "next/image";
<Image
src="/hero.jpg"
alt="Product hero"
fill
sizes="(max-width: 768px) 100vw, 50vw"
priority
/>
Remote images need explicit permission. images.domains has been deprecated since Next.js 14 in favor of remotePatterns, which lets you constrain protocol, hostname and pathname (the Next.js 16 upgrade guide re-flags it; it logs a deprecation warning rather than failing the build):
// next.config.js
module.exports = {
images: {
remotePatterns: [
{ protocol: "https", hostname: "images.example.com", pathname: "/products/**" },
],
},
};
Two further Next.js 16 image changes matter here. The images.qualities default narrowed to [75], so request quality values beyond the default only after adding them to an explicit images.qualities list. And the priority prop is deprecated in favor of preload for the LCP image.
Environment variables: build-time versus runtime
The NEXT_PUBLIC_ prefix is a build-time contract. Any variable with that prefix is inlined into the client bundle when you run next build; its value is frozen into the JavaScript that ships. Server-only variables without the prefix stay on the server and are read at runtime by server components, route handlers and server actions. Two consequences follow. First, changing a NEXT_PUBLIC_ value requires a rebuild; restarting the server changes nothing for the client. Second, a secret prefixed with NEXT_PUBLIC_ is published to every visitor, so the prefix is a promise that the value is not sensitive.
// Read at build time, inlined into the client bundle
const apiBase = process.env.NEXT_PUBLIC_API_BASE;
// Read at runtime, server only
const dbUrl = process.env.DATABASE_URL;
Config hygiene
next.config.js (or .mjs) is the framework's control panel: redirects, headers, image settings, bundler options. Two version-qualified notes keep you current. AMP support was removed in Next.js 16, so AMP-specific config has nothing to configure anymore. And since Next.js 14 the viewport is no longer part of the metadata export: theme color and viewport settings belong in their own export const viewport in layouts and pages.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
A client component reads process.env.NEXT_PUBLIC_API_BASE at module scope. The app was built when the variable was 'https://api-v1.example.com'. You then change .env to 'https://api-v2.example.com' and restart the running production server without rebuilding. What does the browser execute?
Exercise 2Explain
Explain the difference between a build-time NEXT_PUBLIC_ variable and a runtime server-only variable, and why the prefix must never guard a secret.
Reveal the reference answer
reference.textNEXT_PUBLIC_ variables are replaced with their literal values inside the client bundle during next build, so they ship to every visitor and only update on rebuild. Server-only variables are read when server code executes, so they can differ per environment and rotate without a rebuild. Because the prefix inlines the value into downloadable JavaScript, prefixing a secret publishes it to anyone who opens devtools or reads the bundle.Authored expected output: A build-time versus runtime distinction plus the statement that prefixed values are public by construction.
The prefix is a delivery mechanism, not an access-control list. Anything in the client bundle is public.
Exercise 3Implement
Configure next.config.js to allow optimized images from https://images.example.com/products/** only, then write a hero Image component that fills its parent, fetches the right width on mobile and desktop, and is preloaded as the LCP element.
starter.tsx// next.config.js module.exports = { images: { // TODO }, }; // app/page.tsx // TODO: import Image and render the heroReveal the reference answer
reference.tsx// next.config.js module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 'images.example.com', pathname: '/products/**' }, ], }, }; // app/page.tsx import Image from 'next/image'; export default function Page() { return ( <section style={{ position: 'relative', height: '40vh' }}> <Image src="https://images.example.com/products/hero.jpg" alt="Product hero" fill sizes="(max-width: 768px) 100vw, 50vw" preload /> </section> ); }Authored expected output: The remote hero image renders at the container size, the browser downloads a viewport-appropriate variant, and the file is preloaded.
remotePatterns constrains host and path, fill sizes the image to the positioned parent, sizes describes the layout slot, and preload (the Next.js 16 replacement for the deprecated priority) triggers the LCP preload.
Exercise 4Debug
This config logs a deprecation warning and the team wants the supported form. Rewrite it.
starter.jsmodule.exports = { images: { domains: ['cdn.shop.io'], }, };Reveal the reference answer
reference.jsimages.domains has been deprecated since Next.js 14 (the Next.js 16 upgrade guide re-flags it) and emits a deprecation warning; express the allowlist with remotePatterns, which also constrains protocol and path: module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 'cdn.shop.io' }, ], }, };Authored expected output: The deprecation warning is gone and images from cdn.shop.io optimize through the supported remotePatterns allowlist.
remotePatterns is the supported replacement and adds protocol and pathname scoping that the flat domains list never had.
Exercise 5Test
Write a pure helper sizesFor(breakpoints: Array<{ maxWidth: number | null, width: string }>) that builds a sizes attribute string from descending breakpoints, and write assertions for a mobile-first pair: 100vw under 768px and 50vw above, plus an empty array producing ''.
starter.tsexport function sizesFor(breakpoints: Array<{ maxWidth: number | null, width: string }>): string { // TODO } // assertions // expect(sizesFor([{ maxWidth: 768, width: '100vw' }, { maxWidth: null, width: '50vw' }])).toBe('(max-width: 768px) 100vw, 50vw') // expect(sizesFor([])).toBe('')Reveal the reference answer
reference.tsexport function sizesFor(breakpoints: Array<{ maxWidth: number | null, width: string }>): string { return breakpoints .map((b) => (b.maxWidth === null ? b.width : `(max-width: ${b.maxWidth}px) ${b.width}`)) .join(', '); } // Entries with a maxWidth become media conditions; the final unconstrained entry is a bare width. // An empty list joins to the empty string.Authored expected output: Both assertions pass: the joined media-query string and the empty string.
Extracting attribute construction into a pure function makes the sizes contract testable and keeps the component declarative.
Exercise 6Interview
Interview question: a catalog site with 200,000 product photos ships slow pages. Walk through your image strategy end to end, from config to markup to CDN.
Reveal the reference answer
reference.textConfig: allowlist the image CDN with remotePatterns and pin allowed qualities under images.qualities in Next.js 16. Markup: every image goes through next/image with explicit dimensions or fill plus accurate sizes so the browser fetches the smallest adequate variant; preload (the Next.js 16 replacement for the deprecated priority) only on above-the-fold LCP images, lazy everywhere else. Delivery: the optimization pipeline caches derived variants, and a CDN in front serves them from the edge with long-lived immutable headers keyed by URL including size and quality. Process: audit the worst LCP pages first, because a handful of templates usually dominate traffic.Authored expected output: An answer covering config allowlists, correct Image props, priority discipline, CDN caching of variants and measurement-driven prioritization.
Strong answers connect markup-level choices to delivery-level caching instead of treating images as a component detail.
Common misconceptions
#- Setting a NEXT_PUBLIC_ variable in the server environment at runtime changes what clients see. The value is inlined at build time; only a rebuild ships a new value.
- images.domains is still the recommended way to allow remote images. It has been deprecated since Next.js 14; remotePatterns is the supported configuration.
Follow-up practice
#- nextjs-performance-optimization
- nextjs-deployment-capstone
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.