Unverified Commit cdd86546 authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

docs: explain runtime environment app shells

parent 3ff110a9
...@@ -553,6 +553,104 @@ export default async function Page() { ...@@ -553,6 +553,104 @@ export default async function Page() {
} }
``` ```
## Runtime environment variables
**Defer the branch to runtime.** Server-only environment variables are available when server code executes, but reading `process.env` is not a [Request-time API](/docs/app/glossary#request-time-apis). A synchronous environment-dependent branch can therefore run while Next.js prerenders the static shell. Its result, including conditional UI, [`notFound()`](/docs/app/api-reference/functions/not-found), or [`redirect()`](/docs/app/api-reference/functions/redirect), can become part of the build output.
This matters when you build one Docker image and promote it through environments with different values:
```tsx filename="app/music/page.tsx" switcher
import { notFound } from 'next/navigation'
// Before - this branch can run during next build
export default function Page() {
if (process.env.SHOW_MUSIC !== 'true') {
notFound()
}
return <main>Music</main>
}
```
```jsx filename="app/music/page.js" switcher
import { notFound } from 'next/navigation'
// Before - this branch can run during next build
export default function Page() {
if (process.env.SHOW_MUSIC !== 'true') {
notFound()
}
return <main>Music</main>
}
```
A build-time `notFound()` can bake both the not-found UI and a `404` status into the prerendered response. Starting the same image with a different value does not regenerate that output.
When a user-authored route is prerendered with a non-`200` status, `next build` annotates it in the route tree:
```text filename="Terminal"
○ /music [status: 404]
```
This annotation is informational because a prerendered error response can be intentional. If it is unexpected, check for environment-dependent branches that ran with build-time values.
Move the branch into a component that runs after [`io()`](/docs/app/api-reference/functions/io), and wrap it in `<Suspense>`. This keeps the branch out of the build-time shell so it is evaluated during a dynamic render:
```tsx filename="app/music/page.tsx" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { io } from 'next/cache'
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<RuntimeGate />
</Suspense>
)
}
async function RuntimeGate() {
await io()
if (process.env.SHOW_MUSIC !== 'true') {
notFound()
}
return <main>Music</main>
}
```
```jsx filename="app/music/page.js" switcher
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { io } from 'next/cache'
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<RuntimeGate />
</Suspense>
)
}
async function RuntimeGate() {
await io()
if (process.env.SHOW_MUSIC !== 'true') {
notFound()
}
return <main>Music</main>
}
```
Call [`connection()`](/docs/app/api-reference/functions/connection) instead when the code must wait for an actual user navigation. Unlike `connection()`, `io()` can also be used in cache scopes and Client Components. In the uncached Server Component above, both functions leave a hole in runtime prefetches and evaluate the branch during a full dynamic render. Inside a cache scope, `io()` resolves immediately and the cache captures the value at fill time, so keep this environment gate outside cached scopes.
The marker must come before each environment-dependent branch, including branches in nested routes. Deferring only `generateMetadata` does not defer the page component.
Because this gate runs inside `<Suspense>`, its fallback is part of the static shell. If the gate calls `notFound()`, the streamed response remains `200` and Next.js adds a `noindex` tag. With Cache Components, use [`proxy`](/docs/app/api-reference/file-conventions/proxy) for a lightweight request-time check when the HTTP response itself must be `404`. See [Status Codes](/docs/app/api-reference/file-conventions/loading#status-codes) and the [self-hosting environment variable guide](/docs/app/guides/self-hosting#environment-variables).
## `generateStaticParams` and `dynamicParams` ## `generateStaticParams` and `dynamicParams`
Cache Components changes how [dynamic routes](/docs/app/api-reference/file-conventions/dynamic-routes) handle params. Cache Components changes how [dynamic routes](/docs/app/api-reference/file-conventions/dynamic-routes) handle params.
......
...@@ -46,7 +46,7 @@ To read runtime environment variables, we recommend using `getServerSideProps` o ...@@ -46,7 +46,7 @@ To read runtime environment variables, we recommend using `getServerSideProps` o
<AppOnly> <AppOnly>
You safely read environment variables on the server during dynamic rendering. You can safely read environment variables on the server during dynamic rendering.
```tsx filename="app/page.ts" switcher ```tsx filename="app/page.ts" switcher
import { connection } from 'next/server' import { connection } from 'next/server'
...@@ -74,6 +74,10 @@ export default async function Component() { ...@@ -74,6 +74,10 @@ export default async function Component() {
} }
``` ```
Server-only environment variables are read when your server code executes, but reading `process.env` does not by itself opt a route into dynamic rendering. If an environment-dependent branch runs during `next build`, its rendered result can become part of the prerendered output. This includes conditional UI and calls to [`notFound()`](/docs/app/api-reference/functions/not-found) or [`redirect()`](/docs/app/api-reference/functions/redirect).
Place the dynamic marker **before every branch** that must use the runtime value. For example, making `generateMetadata` dynamic does not also make the page component dynamic. With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), use [`io()`](/docs/app/api-reference/functions/io) to mark synchronous, uncached runtime I/O. Use `connection()` when evaluation must wait for an actual user request. See the [runtime environment variable migration guidance](/docs/app/guides/migrating-to-cache-components#runtime-environment-variables) for the Suspense, runtime prefetch, and status-code tradeoffs.
</AppOnly> </AppOnly>
This allows you to use a singular Docker image that can be promoted through multiple environments with different values. This allows you to use a singular Docker image that can be promoted through multiple environments with different values.
......
...@@ -52,6 +52,8 @@ The pattern is similar to per-route code splitting in single-page apps: one arti ...@@ -52,6 +52,8 @@ The pattern is similar to per-route code splitting in single-page apps: one arti
> **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client. > **Good to know**: Routes that read `cookies()` or `headers()` produce an App Shell that includes session data. The framework auto-detects this and caches the shell per session on the client.
An App Shell also includes the result of synchronous branches that run during prerendering. Reading a server-only environment variable does not by itself make a branch request-bound. If build-time and runtime values can differ, call [`io()`](/docs/app/api-reference/functions/io) before the branch so the shell does not capture the build-time result. Use [`connection()`](/docs/app/api-reference/functions/connection) instead when evaluation must wait for an actual user navigation. An uncached branch after either function remains a hole during runtime prefetching and is evaluated during a full dynamic render. This is especially important when the branch calls `notFound()` or `redirect()`. See [Runtime environment variables](/docs/app/guides/migrating-to-cache-components#runtime-environment-variables).
A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL. See [Runtime prefetching](/docs/app/guides/runtime-prefetching).
> **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail. > **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment