Unverified Commit cb30f0a1 authored by Joseph's avatar Joseph Committed by GitHub
parent b6a32bb5
...@@ -63,7 +63,7 @@ Then, add the following scripts to your `package.json` file: ...@@ -63,7 +63,7 @@ Then, add the following scripts to your `package.json` file:
```json filename="package.json" ```json filename="package.json"
{ {
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev --turbopack",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "eslint" "lint": "eslint"
...@@ -73,11 +73,13 @@ Then, add the following scripts to your `package.json` file: ...@@ -73,11 +73,13 @@ Then, add the following scripts to your `package.json` file:
These scripts refer to the different stages of developing an application: These scripts refer to the different stages of developing an application:
- `next dev`: Starts the development server. - `next dev --turbopack`: Starts the development server using Turbopack.
- `next build`: Builds the application for production. - `next build`: Builds the application for production.
- `next start`: Starts the production server. - `next start`: Starts the production server.
- `eslint`: Runs ESLint. - `eslint`: Runs ESLint.
Turbopack is stable for `dev`. For production builds, Turbopack is in beta. To try it, run `next build --turbopack`. See the [Turbopack docs](/docs/app/api-reference/turbopack) for status and caveats.
<AppOnly> <AppOnly>
### Create the `app` directory ### Create the `app` directory
......
...@@ -393,7 +393,11 @@ Calling `redirect` [throws](/docs/app/api-reference/functions/redirect#behavior) ...@@ -393,7 +393,11 @@ Calling `redirect` [throws](/docs/app/api-reference/functions/redirect#behavior)
### Cookies ### Cookies
You can `get`, `set`, and `delete` cookies inside a Server Action using the [`cookies`](/docs/app/api-reference/functions/cookies) API: You can `get`, `set`, and `delete` cookies inside a Server Action using the [`cookies`](/docs/app/api-reference/functions/cookies) API.
When you [set or delete](/docs/app/api-reference/functions/cookies#understanding-cookie-behavior-in-server-actions) a cookie in a Server Action, Next.js re-renders the current page and its layouts on the server so the **UI reflects the new cookie value**.
> **Good to know**: The server update applies to the current React tree, re-rendering, mounting, or unmounting components, as needed. Client state is preserved for re-rendered components, and effects re-run if their dependencies changed.
```ts filename="app/actions.ts" switcher ```ts filename="app/actions.ts" switcher
'use server' 'use server'
......
...@@ -51,7 +51,7 @@ export const metadata: Metadata = { ...@@ -51,7 +51,7 @@ export const metadata: Metadata = {
description: '...', description: '...',
} }
export default function Page() {} export default function Layout() {}
``` ```
```jsx filename="app/blog/layout.tsx" switcher ```jsx filename="app/blog/layout.tsx" switcher
...@@ -60,7 +60,7 @@ export const metadata = { ...@@ -60,7 +60,7 @@ export const metadata = {
description: '...', description: '...',
} }
export default function Page() {} export default function Layout() {}
``` ```
You can view a full list of available options, in the [`generateMetadata` documentation](/docs/app/api-reference/functions/generate-metadata#metadata-fields). You can view a full list of available options, in the [`generateMetadata` documentation](/docs/app/api-reference/functions/generate-metadata#metadata-fields).
......
...@@ -109,7 +109,7 @@ export default function Page() { ...@@ -109,7 +109,7 @@ export default function Page() {
return <h1>Hello, Next.js!</h1> return <h1>Hello, Next.js!</h1>
} }
// ❌ Conflict // Conflict
// `app/route.ts` // `app/route.ts`
export async function POST(request: Request) {} export async function POST(request: Request) {}
``` ```
...@@ -119,7 +119,7 @@ export default function Page() { ...@@ -119,7 +119,7 @@ export default function Page() {
return <h1>Hello, Next.js!</h1> return <h1>Hello, Next.js!</h1>
} }
// ❌ Conflict // Conflict
// `app/route.js` // `app/route.js`
export async function POST(request) {} export async function POST(request) {}
``` ```
...@@ -164,7 +164,7 @@ Using fetch with `options.cache`, `options.next.revalidate`, or `options.next.ta ...@@ -164,7 +164,7 @@ Using fetch with `options.cache`, `options.next.revalidate`, or `options.next.ta
### Convention ### Convention
Use the file `middleware.ts` (or `.js`) in the root of your project to define Middleware. For example, at the same level as `pages` or `app`, or inside `src` if applicable. Create a `middleware.ts` (or `.js`) file in the project root, or inside `src` if applicable, so that it is located at the same level as `pages` or `app`.
> **Note**: While only one `middleware.ts` file is supported per project, you can still organize your middleware logic into modules. Break out middleware functionalities into separate `.ts` or `.js` files and import them into your main `middleware.ts` file. This allows for cleaner management of route-specific middleware, aggregated in the `middleware.ts` for centralized control. By enforcing a single middleware file, it simplifies configuration, prevents potential conflicts, and optimizes performance by avoiding multiple middleware layers. > **Note**: While only one `middleware.ts` file is supported per project, you can still organize your middleware logic into modules. Break out middleware functionalities into separate `.ts` or `.js` files and import them into your main `middleware.ts` file. This allows for cleaner management of route-specific middleware, aggregated in the `middleware.ts` for centralized control. By enforcing a single middleware file, it simplifies configuration, prevents potential conflicts, and optimizes performance by avoiding multiple middleware layers.
......
...@@ -647,6 +647,15 @@ export function middleware(request) { ...@@ -647,6 +647,15 @@ export function middleware(request) {
## Security ## Security
### Working with headers
Be deliberate about where headers go, and avoid directly passing incoming request headers to the outgoing response.
- **Upstream request headers**: In Middleware, `NextResponse.next({ request: { headers } })` modifies the headers your server receives and does not expose them to the client.
- **Response headers**: `new Response(..., { headers })`, `NextResponse.json(..., { headers })`, `NextResponse.next({ headers })`, or `response.headers.set(...)` send headers back to the client. If sensitive values were appended to these headers, they will be visible to clients.
Learn more in [NextResponse headers in Middleware](/docs/app/api-reference/functions/next-response#next).
### Rate limiting ### Rate limiting
You can implement rate limiting in your Next.js backend. In addition to code-based checks, enable any rate limiting features provided by your host. You can implement rate limiting in your Next.js backend. In addition to code-based checks, enable any rate limiting features provided by your host.
......
...@@ -548,7 +548,7 @@ export function middleware(request: NextRequest) { ...@@ -548,7 +548,7 @@ export function middleware(request: NextRequest) {
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ''}; script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ''};
style-src 'self' 'nonce-${nonce}' ${isDev ? "'unsafe-inline'" : ''}; style-src 'self' ${isDev ? "'unsafe-inline'" : `'nonce-${nonce}'`};
img-src 'self' blob: data:; img-src 'self' blob: data:;
font-src 'self'; font-src 'self';
object-src 'none'; object-src 'none';
...@@ -570,7 +570,7 @@ export function middleware(request) { ...@@ -570,7 +570,7 @@ export function middleware(request) {
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ''}; script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ''};
style-src 'self' 'nonce-${nonce}' ${isDev ? "'unsafe-inline'" : ''}; style-src 'self' ${isDev ? "'unsafe-inline'" : `'nonce-${nonce}'`};
img-src 'self' blob: data:; img-src 'self' blob: data:;
font-src 'self'; font-src 'self';
object-src 'none'; object-src 'none';
......
...@@ -251,6 +251,10 @@ yarn add server-only ...@@ -251,6 +251,10 @@ yarn add server-only
pnpm add server-only pnpm add server-only
``` ```
```bash package="bun"
bun add server-only
```
```ts filename="lib/data.ts" ```ts filename="lib/data.ts"
import 'server-only' import 'server-only'
......
...@@ -97,7 +97,7 @@ Here's how this example works: ...@@ -97,7 +97,7 @@ Here's how this example works:
3. After 60 seconds has passed, the next request will still return the cached (now stale) page 3. After 60 seconds has passed, the next request will still return the cached (now stale) page
4. The cache is invalidated and a new version of the page begins generating in the background 4. The cache is invalidated and a new version of the page begins generating in the background
5. Once generated successfully, the next request will return the updated page and cache it for subsequent requests 5. Once generated successfully, the next request will return the updated page and cache it for subsequent requests
6. If `/blog/26` is requested, and it exists, the page will be generated on-demand. This behavior can be changed by using a different [dynamicParams](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) value. However, if the post does not exist, then 404 is returned. 6. If `/blog/26` is requested, and it exists, the page will be generated on-demand. This behavior can be changed by using a different [dynamicParams](/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams) value. However, if the post does not exist, then 404 is returned.
</AppOnly> </AppOnly>
...@@ -196,7 +196,7 @@ Here's how this example works: ...@@ -196,7 +196,7 @@ Here's how this example works:
3. After 60 seconds has passed, the next request will still return the cached (now stale) page 3. After 60 seconds has passed, the next request will still return the cached (now stale) page
4. The cache is invalidated and a new version of the page begins generating in the background 4. The cache is invalidated and a new version of the page begins generating in the background
5. Once generated successfully, the next request will return the updated page and cache it for subsequent requests 5. Once generated successfully, the next request will return the updated page and cache it for subsequent requests
6. If `/blog/26` is requested, and it exists, the page will be generated on-demand. This behavior can be changed by using a different [fallback](https://nextjs.org/docs/pages/api-reference/functions/get-static-paths#fallback-false) value. However, if the post does not exist, then 404 is returned. 6. If `/blog/26` is requested, and it exists, the page will be generated on-demand. This behavior can be changed by using a different [fallback](/docs/pages/api-reference/functions/get-static-paths#fallback-false) value. However, if the post does not exist, then 404 is returned.
</PagesOnly> </PagesOnly>
......
...@@ -215,3 +215,4 @@ export default async function RootLayout({ children, params }) { ...@@ -215,3 +215,4 @@ export default async function RootLayout({ children, params }) {
- [`paraglide-next`](https://inlang.com/m/osslbuzt/paraglide-next-i18n) - [`paraglide-next`](https://inlang.com/m/osslbuzt/paraglide-next-i18n)
- [`lingui`](https://lingui.dev) - [`lingui`](https://lingui.dev)
- [`tolgee`](https://tolgee.io/apps-integrations/next) - [`tolgee`](https://tolgee.io/apps-integrations/next)
- [`next-intlayer`](https://intlayer.org/doc/environment/nextjs)
...@@ -181,16 +181,16 @@ It provides detailed information about the time taken for each module to compile ...@@ -181,16 +181,16 @@ It provides detailed information about the time taken for each module to compile
1. Navigate around your application or make edits to files to reproduce the problem. 1. Navigate around your application or make edits to files to reproduce the problem.
1. Stop the Next.js development server. 1. Stop the Next.js development server.
1. A file called `trace-turbopack` will be available in the `.next` folder. 1. A file called `trace-turbopack` will be available in the `.next` folder.
1. You can interpret the file using `next internal trace [path-to-file]`: 1. You can interpret the file using `npx next internal trace [path-to-file]`:
```bash ```bash
next internal trace .next/trace-turbopack npx next internal trace .next/trace-turbopack
``` ```
On versions where `trace` is not available, the command was named `turbo-trace-server`: On versions where `trace` is not available, the command was named `turbo-trace-server`:
```bash ```bash
next internal turbo-trace-server .next/trace-turbopack npx next internal turbo-trace-server .next/trace-turbopack
``` ```
1. Once the trace server is running you can view the trace at https://trace.nextjs.org/. 1. Once the trace server is running you can view the trace at https://trace.nextjs.org/.
......
...@@ -70,7 +70,7 @@ const nextConfig = { ...@@ -70,7 +70,7 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
Next.js also optimizes some libraries automatically, thus they do not need to be included in the optimizePackageImports list. See the [full list](https://nextjs.org/docs/app/api-reference/config/next-config-js/optimizePackageImports). Next.js also optimizes some libraries automatically, thus they do not need to be included in the optimizePackageImports list. See the [full list](/docs/app/api-reference/config/next-config-js/optimizePackageImports).
<PagesOnly> <PagesOnly>
......
...@@ -96,7 +96,7 @@ To embed videos from external platforms, you can use Next.js to fetch the video ...@@ -96,7 +96,7 @@ To embed videos from external platforms, you can use Next.js to fetch the video
**1. Create a Server Component for video embedding** **1. Create a Server Component for video embedding**
The first step is to create a [Server Component](https://nextjs.org/docs/app/getting-started/server-and-client-components) that generates the appropriate iframe for embedding the video. This component will fetch the source URL for the video and render the iframe. The first step is to create a [Server Component](/docs/app/getting-started/server-and-client-components) that generates the appropriate iframe for embedding the video. This component will fetch the source URL for the video and render the iframe.
```jsx filename="app/ui/video-component.jsx" ```jsx filename="app/ui/video-component.jsx"
export default async function VideoComponent() { export default async function VideoComponent() {
...@@ -108,7 +108,7 @@ export default async function VideoComponent() { ...@@ -108,7 +108,7 @@ export default async function VideoComponent() {
**2. Stream the video component using React Suspense** **2. Stream the video component using React Suspense**
After creating the Server Component to embed the video, the next step is to [stream](https://nextjs.org/docs/app/api-reference/file-conventions/loading) the component using [React Suspense](https://react.dev/reference/react/Suspense). After creating the Server Component to embed the video, the next step is to [stream](/docs/app/api-reference/file-conventions/loading) the component using [React Suspense](https://react.dev/reference/react/Suspense).
```jsx filename="app/page.jsx" ```jsx filename="app/page.jsx"
import { Suspense } from 'react' import { Suspense } from 'react'
......
...@@ -82,6 +82,9 @@ export default function Page() { ...@@ -82,6 +82,9 @@ export default function Page() {
} }
``` ```
> **Good to know**: For security reasons, the Image Optimization API using the default [loader](#loader) will _not_ forward headers when fetching the `src` image.
> If the `src` image requires authentication, consider using the [unoptimized](#unoptimized) property to disable Image Optimization.
#### `alt` #### `alt`
The `alt` property is used to describe the image for screen readers and search engines. It is also the fallback text if images have been disabled or an error occurs while loading the image. The `alt` property is used to describe the image for screen readers and search engines. It is also the fallback text if images have been disabled or an error occurs while loading the image.
...@@ -527,7 +530,7 @@ module.exports = { ...@@ -527,7 +530,7 @@ module.exports = {
} }
``` ```
If using a version prior to 15.3.0, you can configure `remotePatterns` using the object: You can also configure `remotePatterns` using the object:
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
...@@ -863,7 +866,7 @@ The `getImageProps` function can be used to get the props that would be passed t ...@@ -863,7 +866,7 @@ The `getImageProps` function can be used to get the props that would be passed t
```jsx ```jsx
import { getImageProps } from 'next/image' import { getImageProps } from 'next/image'
const props = getImageProps({ const { props } = getImageProps({
src: 'https://example.com/image.jpg', src: 'https://example.com/image.jpg',
alt: 'A scenic mountain view', alt: 'A scenic mountain view',
width: 1200, width: 1200,
......
...@@ -58,6 +58,7 @@ The following props can be passed to the `<Link>` component: ...@@ -58,6 +58,7 @@ The following props can be passed to the `<Link>` component:
| Prop | Example | Type | Required | | Prop | Example | Type | Required |
| ----------------------------------- | ------------------------ | ----------------- | -------- | | ----------------------------------- | ------------------------ | ----------------- | -------- |
| [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes | | [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes |
| [`as`](#as) | `as="/post/abc"` | String or Object | - |
| [`replace`](#replace) | `replace={false}` | Boolean | - | | [`replace`](#replace) | `replace={false}` | Boolean | - |
| [`scroll`](#scroll) | `scroll={false}` | Boolean | - | | [`scroll`](#scroll) | `scroll={false}` | Boolean | - |
| [`prefetch`](#prefetch) | `prefetch={false}` | Boolean | - | | [`prefetch`](#prefetch) | `prefetch={false}` | Boolean | - |
...@@ -452,6 +453,12 @@ export default function Home() { ...@@ -452,6 +453,12 @@ export default function Home() {
} }
``` ```
### `as`
Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://github.com/vercel/next.js/blob/v9.5.2/docs/api-reference/next/link.md#dynamic-routes) to see how it worked.
When this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://github.com/vercel/next.js/blob/v9.5.2/docs/api-reference/next/link.md#dynamic-routes).
</PagesOnly> </PagesOnly>
### `onNavigate` ### `onNavigate`
......
...@@ -69,4 +69,4 @@ export default function manifest() { ...@@ -69,4 +69,4 @@ export default function manifest() {
### Manifest Object ### Manifest Object
The manifest object contains an extensive list of options that may be updated due to new web standards. For information on all the current options, refer to the `MetadataRoute.Manifest` type in your code editor if using [TypeScript](https://nextjs.org/docs/app/api-reference/config/typescript#ide-plugin) or see the [MDN](https://developer.mozilla.org/docs/Web/Manifest) docs. The manifest object contains an extensive list of options that may be updated due to new web standards. For information on all the current options, refer to the `MetadataRoute.Manifest` type in your code editor if using [TypeScript](/docs/app/api-reference/config/typescript#ide-plugin) or see the [MDN](https://developer.mozilla.org/docs/Web/Manifest) docs.
...@@ -113,6 +113,8 @@ The difference between **catch-all** and **optional catch-all** segments is that ...@@ -113,6 +113,8 @@ The difference between **catch-all** and **optional catch-all** segments is that
When using TypeScript, you can add types for `params` depending on your configured route segment — use [`PageProps<'/route'>`](/docs/app/api-reference/file-conventions/page#page-props-helper), [`LayoutProps<'/route'>`](/docs/app/api-reference/file-conventions/layout#layout-props-helper), or [`RouteContext<'/route'>`](/docs/app/api-reference/file-conventions/route#route-context-helper) to type `params` in `page`, `layout`, and `route` respectively. When using TypeScript, you can add types for `params` depending on your configured route segment — use [`PageProps<'/route'>`](/docs/app/api-reference/file-conventions/page#page-props-helper), [`LayoutProps<'/route'>`](/docs/app/api-reference/file-conventions/layout#layout-props-helper), or [`RouteContext<'/route'>`](/docs/app/api-reference/file-conventions/route#route-context-helper) to type `params` in `page`, `layout`, and `route` respectively.
Route `params` values are typed as `string`, `string[]`, or `undefined` (for optional catch-all segments), because their values aren't known until runtime. Users can enter any URL into the address bar, and these broad types help ensure that your application code handles all these possible cases.
| Route | `params` Type Definition | | Route | `params` Type Definition |
| ----------------------------------- | ---------------------------------------- | | ----------------------------------- | ---------------------------------------- |
| `app/blog/[slug]/page.js` | `{ slug: string }` | | `app/blog/[slug]/page.js` | `{ slug: string }` |
...@@ -120,6 +122,24 @@ When using TypeScript, you can add types for `params` depending on your configur ...@@ -120,6 +122,24 @@ When using TypeScript, you can add types for `params` depending on your configur
| `app/shop/[[...slug]]/page.js` | `{ slug?: string[] }` | | `app/shop/[[...slug]]/page.js` | `{ slug?: string[] }` |
| `app/[categoryId]/[itemId]/page.js` | `{ categoryId: string, itemId: string }` | | `app/[categoryId]/[itemId]/page.js` | `{ categoryId: string, itemId: string }` |
If you're working on a route where `params` can only have a fixed number of valid values, such as a `[locale]` param with a known set of language codes, you can use runtime validation to handle any invalid params a user may enter, and let the rest of your application work with the narrower type from your known set.
```tsx filename="/app/[locale]/page.tsx"
import { notFound } from 'next/navigation'
import type { Locale } from '@i18n/types'
import { isValidLocale } from '@i18n/utils'
function assertValidLocale(value: string): asserts value is Locale {
if (!isValidLocale(value)) notFound()
}
export default async function Page(props: PageProps<'/[locale]'>) {
const { locale } = await props.params // locale is typed as string
assertValidLocale(locale)
// locale is now typed as Locale
}
```
## Behavior ## Behavior
- Since the `params` prop is a promise. You must use `async`/`await` or React's use function to access the values. - Since the `params` prop is a promise. You must use `async`/`await` or React's use function to access the values.
......
...@@ -61,7 +61,7 @@ A promise that resolves to an object containing the [dynamic route parameters](/ ...@@ -61,7 +61,7 @@ A promise that resolves to an object containing the [dynamic route parameters](/
```tsx filename="app/dashboard/[team]/layout.tsx" switcher ```tsx filename="app/dashboard/[team]/layout.tsx" switcher
export default async function Layout({ export default async function Layout({
children children,
params, params,
}: { }: {
children: React.ReactNode children: React.ReactNode
...@@ -234,7 +234,7 @@ export default function Layout({ children }) { ...@@ -234,7 +234,7 @@ export default function Layout({ children }) {
Layouts do not re-render on navigation, so they do not access pathname which would otherwise become stale. Layouts do not re-render on navigation, so they do not access pathname which would otherwise become stale.
To access the current pathname, you can read it inside a Client Component using the [`usePathname`](https://nextjs.org/docs/app/api-reference/functions/use-pathname) hook. Since Client Components re-render during navigation, they have access to the latest pathname. To access the current pathname, you can read it inside a Client Component using the [`usePathname`](/docs/app/api-reference/functions/use-pathname) hook. Since Client Components re-render during navigation, they have access to the latest pathname.
```tsx filename="app/ui/breadcrumbs.tsx" switcher ```tsx filename="app/ui/breadcrumbs.tsx" switcher
'use client' 'use client'
...@@ -312,7 +312,7 @@ export default function Layout({ children }) { ...@@ -312,7 +312,7 @@ export default function Layout({ children }) {
Layouts cannot pass data to their `children`. However, you can fetch the same data in a route more than once, and use React [`cache`](https://react.dev/reference/react/cache) to dedupe the requests without affecting performance. Layouts cannot pass data to their `children`. However, you can fetch the same data in a route more than once, and use React [`cache`](https://react.dev/reference/react/cache) to dedupe the requests without affecting performance.
Alternatively, when using [`fetch`](https://nextjs.org/docs/app/api-reference/functions/fetch)in Next.js, requests are automatically deduped. Alternatively, when using [`fetch`](/docs/app/api-reference/functions/fetch)in Next.js, requests are automatically deduped.
```tsx filename="app/lib/data.ts" switcher ```tsx filename="app/lib/data.ts" switcher
export async function getUser(id: string) { export async function getUser(id: string) {
......
...@@ -8,11 +8,17 @@ related: ...@@ -8,11 +8,17 @@ related:
- app/api-reference/functions/next-response - app/api-reference/functions/next-response
--- ---
The `middleware.js|ts` file is used to write [Middleware](/docs/app/api-reference/file-conventions/middleware) and run code on the server before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly. The `middleware.js|ts` file is used to write [Middleware](/docs/app/getting-started/route-handlers-and-middleware#middleware) and run code on the server before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
Middleware executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects. Middleware executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects.
Use the file `middleware.ts` (or .js) in the root of your project to define Middleware. For example, at the same level as `app` or `pages`, or inside `src` if applicable. > **Good to know**:
>
> Middleware is meant to be invoked separately of your render code and in optimized cases deployed to your CDN for fast redirect/rewrite handling, you should not attempt relying on shared modules or globals.
>
> To pass information from Middleware to your application, use [headers](#setting-headers), [cookies](#using-cookies), [rewrites](/docs/app/api-reference/functions/next-response#rewrite), [redirects](/docs/app/api-reference/functions/next-response#redirect), or the URL.
Create a `middleware.ts` (or `.js`) file in the project root, or inside `src` if applicable, so that it is located at the same level as `pages` or `app`.
```tsx filename="middleware.ts" switcher ```tsx filename="middleware.ts" switcher
import { NextResponse, NextRequest } from 'next/server' import { NextResponse, NextRequest } from 'next/server'
...@@ -281,7 +287,7 @@ export function middleware(request) { ...@@ -281,7 +287,7 @@ export function middleware(request) {
} }
``` ```
## Using Cookies ### Using Cookies
Cookies are regular headers. On a `Request`, they are stored in the `Cookie` header. On a `Response` they are in the `Set-Cookie` header. Next.js provides a convenient way to access and manipulate these cookies through the `cookies` extension on `NextRequest` and `NextResponse`. Cookies are regular headers. On a `Request`, they are stored in the `Cookie` header. On a `Response` they are in the `Set-Cookie` header. Next.js provides a convenient way to access and manipulate these cookies through the `cookies` extension on `NextRequest` and `NextResponse`.
...@@ -400,6 +406,13 @@ export function middleware(request) { ...@@ -400,6 +406,13 @@ export function middleware(request) {
} }
``` ```
Note that the snippet uses:
- `NextResponse.next({ request: { headers: requestHeaders } })` to make `requestHeaders` available upstream
- **NOT** `NextResponse.next({ headers: requestHeaders })` which makes `requestHeaders` available to clients
Learn more in [NextResponse headers in Middleware](/docs/app/api-reference/functions/next-response#next).
> **Good to know**: Avoid setting large headers as it might cause [431 Request Header Fields Too Large](https://developer.mozilla.org/docs/Web/HTTP/Status/431) error depending on your backend web server configuration. > **Good to know**: Avoid setting large headers as it might cause [431 Request Header Fields Too Large](https://developer.mozilla.org/docs/Web/HTTP/Status/431) error depending on your backend web server configuration.
### CORS ### CORS
...@@ -673,6 +686,7 @@ Learn how to [configure Middleware](/docs/app/guides/self-hosting#middleware) wh ...@@ -673,6 +686,7 @@ Learn how to [configure Middleware](/docs/app/guides/self-hosting#middleware) wh
| Version | Changes | | Version | Changes |
| --------- | --------------------------------------------------------------------------------------------- | | --------- | --------------------------------------------------------------------------------------------- |
| `v15.5.0` | Middleware can now use the Node.js runtime (stable) |
| `v15.2.0` | Middleware can now use the Node.js runtime (experimental) | | `v15.2.0` | Middleware can now use the Node.js runtime (experimental) |
| `v13.1.0` | Advanced Middleware flags added | | `v13.1.0` | Advanced Middleware flags added |
| `v13.0.0` | Middleware can modify request headers, response headers, and send responses | | `v13.0.0` | Middleware can modify request headers, response headers, and send responses |
......
...@@ -5,7 +5,7 @@ description: API Reference for the after function. ...@@ -5,7 +5,7 @@ description: API Reference for the after function.
`after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics. `after` allows you to schedule work to be executed after a response (or prerender) is finished. This is useful for tasks and other side effects that should not block the response, such as logging and analytics.
It can be used in [Server Components](/docs/app/getting-started/server-and-client-components) (including [`generateMetadata`](https://nextjs.org/docs/app/api-reference/functions/generate-metadata)), [Server Actions](/docs/app/getting-started/updating-data), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Middleware](/docs/app/api-reference/file-conventions/middleware). It can be used in [Server Components](/docs/app/getting-started/server-and-client-components) (including [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata)), [Server Actions](/docs/app/getting-started/updating-data), [Route Handlers](/docs/app/api-reference/file-conventions/route), and [Middleware](/docs/app/api-reference/file-conventions/middleware).
The function accepts a callback that will be executed after the response (or prerender) is finished: The function accepts a callback that will be executed after the response (or prerender) is finished:
......
...@@ -82,6 +82,14 @@ When working with cookies in Server Components, it's important to understand tha ...@@ -82,6 +82,14 @@ When working with cookies in Server Components, it's important to understand tha
The server can only send instructions (via `Set-Cookie` headers) to tell the browser to store cookies - the actual storage happens on the client side. This is why cookie operations that modify state (`.set`, `.delete`, `.clear`) must be performed in a Route Handler or Server Action where the response headers can be properly set. The server can only send instructions (via `Set-Cookie` headers) to tell the browser to store cookies - the actual storage happens on the client side. This is why cookie operations that modify state (`.set`, `.delete`, `.clear`) must be performed in a Route Handler or Server Action where the response headers can be properly set.
## Understanding Cookie Behavior in Server Actions
After you set or delete a cookie in a Server Action, Next.js re-renders the current page and its layouts on the server so the UI reflects the new cookie value. See the [Caching guide](/docs/app/guides/caching#cookies).
The UI is not unmounted, but effects that depend on data coming from the server will re-run.
To refresh cached data too, call [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) inside the action.
## Examples ## Examples
### Getting a cookie ### Getting a cookie
......
...@@ -79,7 +79,7 @@ Set the cache lifetime of a resource (in seconds). [Data Cache](/docs/app/guides ...@@ -79,7 +79,7 @@ Set the cache lifetime of a resource (in seconds). [Data Cache](/docs/app/guides
fetch(`https://...`, { next: { tags: ['collection'] } }) fetch(`https://...`, { next: { tags: ['collection'] } })
``` ```
Set the cache tags of a resource. Data can then be revalidated on-demand using [`revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag). The max length for a custom tag is 256 characters and the max tag items is 128. Set the cache tags of a resource. Data can then be revalidated on-demand using [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag). The max length for a custom tag is 256 characters and the max tag items is 128.
## Troubleshooting ## Troubleshooting
......
...@@ -127,7 +127,7 @@ import { NextResponse } from 'next/server' ...@@ -127,7 +127,7 @@ import { NextResponse } from 'next/server'
return NextResponse.next() return NextResponse.next()
``` ```
You can also forward `headers` when producing the response: You can also forward `headers` upstream when producing the response, using `NextResponse.next({ request: { headers } })`:
```ts ```ts
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
...@@ -136,7 +136,7 @@ import { NextResponse } from 'next/server' ...@@ -136,7 +136,7 @@ import { NextResponse } from 'next/server'
const newHeaders = new Headers(request.headers) const newHeaders = new Headers(request.headers)
// Add a new header // Add a new header
newHeaders.set('x-version', '123') newHeaders.set('x-version', '123')
// And produce a response with the new headers // Forward the modified request headers upstream
return NextResponse.next({ return NextResponse.next({
request: { request: {
// New request headers // New request headers
...@@ -144,3 +144,49 @@ return NextResponse.next({ ...@@ -144,3 +144,49 @@ return NextResponse.next({
}, },
}) })
``` ```
This forwards `newHeaders` upstream to the target page, route, or server action, and does not expose them to the client. While this pattern is useful for passing data upstream, it should be used with caution because the headers containing this data may be forwarded to external services.
In contrast, `NextResponse.next({ headers })` is a shorthand for sending headers from middleware to the client. This is **NOT** good practice and should be avoided. Among other reasons because setting response headers like `Content-Type`, can override framework expectations (for example, the `Content-Type` used by Server Actions), leading to failed submissions or broken streaming responses.
```ts
import { type NextRequest, NextResponse } from 'next/server'
async function middleware(request: NextRequest) {
const headers = await injectAuth(request.headers)
// DO NOT forward headers like this
return NextResponse.next({ headers })
}
```
In general, avoid copying all incoming request headers because doing so can leak sensitive data to clients or upstream services.
Prefer a defensive approach by creating a subset of incoming request headers using an allow-list. For example, you might discard custom `x-*` headers and only forward known-safe headers:
```ts
import { type NextRequest, NextResponse } from 'next/server'
function middleware(request: NextRequest) {
const incoming = new Headers(request.headers)
const forwarded = new Headers()
for (const [name, value] of incoming) {
const headerName = name.toLowerCase()
// Keep only known-safe headers, discard custom x-* and other sensitive ones
if (
!headerName.startsWith('x-') &&
headerName !== 'authorization' &&
headerName !== 'cookie'
) {
// Preserve original header name casing
forwarded.set(name, value)
}
}
return NextResponse.next({
request: {
headers: forwarded,
},
})
}
```
...@@ -13,7 +13,7 @@ description: API Reference for the revalidatePath function. ...@@ -13,7 +13,7 @@ description: API Reference for the revalidatePath function.
> **Good to know**: > **Good to know**:
> >
> - **Server Functions**: Updates the UI immediately (if viewing the revalidated path). Currently, it also causes all previously visited pages to refresh when navigated to again. This behavior is temporary and will be updated in the future to apply only to the specific path. > - **Server Functions**: Updates the UI immediately (if viewing the affected path). Currently, it also causes all previously visited pages to refresh when navigated to again. This behavior is temporary and will be updated in the future to apply only to the specific path.
> - **Route Handlers**: Marks the path for revalidation. The revalidation is done on the next visit to the specified path. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited. > - **Route Handlers**: Marks the path for revalidation. The revalidation is done on the next visit to the specified path. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.
## Parameters ## Parameters
...@@ -22,8 +22,10 @@ description: API Reference for the revalidatePath function. ...@@ -22,8 +22,10 @@ description: API Reference for the revalidatePath function.
revalidatePath(path: string, type?: 'page' | 'layout'): void; revalidatePath(path: string, type?: 'page' | 'layout'): void;
``` ```
- `path`: Either a string representing the filesystem path associated with the data you want to revalidate (for example, `/product/[slug]/page`), or the literal route segment (for example, `/product/123`). Must not exceed 1024 characters. This value is case-sensitive. - `path`: Either a route pattern corresponding to the data you want to revalidate, for example `/product/[slug]`, or a specific URL, `/product/123`. Do not append `/page` or `/layout`, use the `type` parameter instead. Must not exceed 1024 characters. This value is case-sensitive.
- `type`: (optional) `'page'` or `'layout'` string to change the type of path to revalidate. If `path` contains a dynamic segment (for example, `/product/[slug]/page`), this parameter is required. If path refers to the literal route segment, e.g., `/product/1` for a dynamic page (e.g., `/product/[slug]/page`), you should not provide `type`. - `type`: (optional) `'page'` or `'layout'` string to change the type of path to revalidate. If `path` contains a dynamic segment, for example `/product/[slug]`, this parameter is required. If `path` is a specific URL, `/product/1`, omit `type`.
Use a specific URL when you want to refresh a [single page](#revalidating-a-specific-url). Use a route pattern plus `type` to refresh [multiple URLs](#revalidating-a-page-path).
## Returns ## Returns
...@@ -34,7 +36,7 @@ revalidatePath(path: string, type?: 'page' | 'layout'): void; ...@@ -34,7 +36,7 @@ revalidatePath(path: string, type?: 'page' | 'layout'): void;
The path parameter can point to pages, layouts, or route handlers: The path parameter can point to pages, layouts, or route handlers:
- **Pages**: Invalidates the specific page - **Pages**: Invalidates the specific page
- **Layouts**: Invalidates the layout and all pages beneath it - **Layouts**: Invalidates the layout (the `layout.tsx` at that segment), all nested layouts beneath it, and all pages beneath them
- **Route Handlers**: Invalidates Data Cache entries accessed within route handlers. For example `revalidatePath("/api/data")` invalidates this GET handler: - **Route Handlers**: Invalidates Data Cache entries accessed within route handlers. For example `revalidatePath("/api/data")` invalidates this GET handler:
```ts filename="app/api/data/route.ts" ```ts filename="app/api/data/route.ts"
......
...@@ -65,6 +65,7 @@ const pathname = usePathname() ...@@ -65,6 +65,7 @@ const pathname = usePathname()
```tsx filename="app/example-client-component.tsx" switcher ```tsx filename="app/example-client-component.tsx" switcher
'use client' 'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation' import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() { function ExampleClientComponent() {
...@@ -79,6 +80,7 @@ function ExampleClientComponent() { ...@@ -79,6 +80,7 @@ function ExampleClientComponent() {
```jsx filename="app/example-client-component.js" switcher ```jsx filename="app/example-client-component.js" switcher
'use client' 'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation' import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() { function ExampleClientComponent() {
...@@ -90,6 +92,56 @@ function ExampleClientComponent() { ...@@ -90,6 +92,56 @@ function ExampleClientComponent() {
} }
``` ```
### Avoid hydration mismatch with rewrites
When a page is pre-rendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using `next.config` or `Middleware`, the browser URL may differ, and `usePathname()` will read the rewritten pathname on the client.
To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount.
```tsx filename="app/example-client-component.tsx" switcher
'use client'
import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
export default function PathnameBadge() {
const pathname = usePathname()
const [clientPathname, setClientPathname] = useState('')
useEffect(() => {
setClientPathname(pathname)
}, [pathname])
return (
<p>
Current pathname: <span>{clientPathname}</span>
</p>
)
}
```
```jsx filename="app/example-client-component.js" switcher
'use client'
import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
export default function PathnameBadge() {
const pathname = usePathname()
const [clientPathname, setClientPathname] = useState('')
useEffect(() => {
setClientPathname(pathname)
}, [pathname])
return (
<p>
Current pathname: <span>{clientPathname}</span>
</p>
)
}
```
| Version | Changes | | Version | Changes |
| --------- | ------------------------- | | --------- | ------------------------- |
| `v13.0.0` | `usePathname` introduced. | | `v13.0.0` | `usePathname` introduced. |
...@@ -69,13 +69,15 @@ node .next/standalone/server.js ...@@ -69,13 +69,15 @@ node .next/standalone/server.js
- While tracing in monorepo setups, the project directory is used for tracing by default. For `next build packages/web-app`, `packages/web-app` would be the tracing root and any files outside of that folder will not be included. To include files outside of this folder you can set `outputFileTracingRoot` in your `next.config.js`. - While tracing in monorepo setups, the project directory is used for tracing by default. For `next build packages/web-app`, `packages/web-app` would be the tracing root and any files outside of that folder will not be included. To include files outside of this folder you can set `outputFileTracingRoot` in your `next.config.js`.
```js filename="packages/web-app/next.config.js" ```js filename="packages/web-app/next.config.js"
const path = require('path')
module.exports = { module.exports = {
// this includes files from the monorepo base two directories up // this includes files from the monorepo base two directories up
outputFileTracingRoot: path.join(__dirname, '../../'), outputFileTracingRoot: path.join(__dirname, '../../'),
} }
``` ```
- There are some cases in which Next.js might fail to include required files, or might incorrectly include unused files. In those cases, you can leverage `outputFileTracingExcludes` and `outputFileTracingIncludes` respectively in `next.config.js`. Each config accepts an object with [minimatch globs](https://www.npmjs.com/package/minimatch) for the key to match specific pages and a value of an array with globs relative to the project's root to either include or exclude in the trace. - There are some cases in which Next.js might fail to include required files, or might incorrectly include unused files. In those cases, you can leverage `outputFileTracingExcludes` and `outputFileTracingIncludes` respectively in `next.config.js`. Each option accepts an object whose keys are **route globs** (matched with [picomatch](https://www.npmjs.com/package/picomatch#basic-globbing) against the route path, e.g. `/api/hello`) and whose values are **glob patterns resolved from the project root** that specify files to include or exclude in the trace.
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
...@@ -91,4 +93,63 @@ module.exports = { ...@@ -91,4 +93,63 @@ module.exports = {
} }
``` ```
**Note:** The key of `outputFileTracingIncludes`/`outputFileTracingExcludes` is a [glob](https://www.npmjs.com/package/picomatch#basic-globbing), so special characters need to be escaped. Using a `src/` directory does not change how you write these options:
- **Keys** still match the route path (`'/api/hello'`, `'/products/[id]'`, etc.).
- **Values** can reference paths under `src/` since they are resolved relative to the project root.
```js filename="next.config.js"
module.exports = {
outputFileTracingIncludes: {
'/products/*': ['src/lib/payments/**/*'],
'/*': ['src/config/runtime/**/*.json'],
},
outputFileTracingExcludes: {
'/api/*': ['src/temp/**/*', 'public/large-logs/**/*'],
},
}
```
You can also target all routes using a global key like `'/*'`:
```js filename="next.config.js"
module.exports = {
outputFileTracingIncludes: {
'/*': ['src/i18n/locales/**/*.json'],
},
}
```
These options are applied to server traces and do not affect routes that do not produce a server trace file:
- Edge Runtime routes are not affected.
- Fully static pages are not affected.
In monorepos or when you need to include files outside the app folder, combine `outputFileTracingRoot` with includes:
```js filename="next.config.js"
const path = require('path')
module.exports = {
// Trace from the monorepo root
outputFileTracingRoot: path.join(__dirname, '../../'),
outputFileTracingIncludes: {
'/route1': ['../shared/assets/**/*'],
},
}
```
> **Good to know**:
>
> - Prefer forward slashes (`/`) in patterns for cross-platform compatibility.
> - Keep patterns as narrow as possible to avoid oversized traces (avoid `**/*` at the repo root).
Common include patterns for native/runtime assets:
```js filename="next.config.js"
module.exports = {
outputFileTracingIncludes: {
'/*': ['node_modules/sharp/**/*', 'node_modules/aws-crt/dist/bin/**/*'],
},
}
```
...@@ -111,12 +111,14 @@ const nextConfig = { ...@@ -111,12 +111,14 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
<AppOnly>
### Statically Typed Links ### Statically Typed Links
Next.js can statically type links to prevent typos and other errors when using `next/link`, improving type safety when navigating between pages. Next.js can statically type links to prevent typos and other errors when using `next/link`, improving type safety when navigating between pages.
Works in both the Pages and App Router for the `href` prop in `next/link`. In the App Router, it also types `next/navigation` methods like `push`, `replace`, and `prefetch`. It does not type `next/router` methods in Pages Router.
Literal `href` strings are validated, while non-literal `href`s may require a cast with `as Route`.
To opt-into this feature, `typedRoutes` need to be enabled and the project needs to be using TypeScript. To opt-into this feature, `typedRoutes` need to be enabled and the project needs to be using TypeScript.
```ts filename="next.config.ts" ```ts filename="next.config.ts"
...@@ -131,20 +133,61 @@ export default nextConfig ...@@ -131,20 +133,61 @@ export default nextConfig
Next.js will generate a link definition in `.next/types` that contains information about all existing routes in your application, which TypeScript can then use to provide feedback in your editor about invalid links. Next.js will generate a link definition in `.next/types` that contains information about all existing routes in your application, which TypeScript can then use to provide feedback in your editor about invalid links.
Currently, experimental support includes any string literal, including dynamic segments. For non-literal strings, you currently need to manually cast the `href` with `as Route`: > **Good to know**: If you set up your project without `create-next-app`, ensure the generated Next.js types are included by adding `.next/types/**/*.ts` to the `include` array in your `tsconfig.json`:
```tsx {/* prettier-ignore-start */}
import type { Route } from 'next';
```json filename="tsconfig.json" highlight={4}
{
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": ["node_modules"]
}
```
{/* prettier-ignore-end */}
Currently, support includes any string literal, including dynamic segments. For non-literal strings, you need to manually cast with `as Route`. The example below shows both `next/link` and `next/navigation` usage:
```tsx filename="app/example-client.tsx"
'use client'
import type { Route } from 'next'
import Link from 'next/link' import Link from 'next/link'
import { useRouter } from 'next/navigation'
// No TypeScript errors if href is a valid route export default function Example() {
<Link href="/about" /> const router = useRouter()
<Link href="/blog/nextjs" /> const slug = 'nextjs'
<Link href={`/blog/${slug}`} />
<Link href={('/blog' + slug) as Route} />
// TypeScript errors if href is not a valid route return (
<Link href="/aboot" /> <>
{/* Link: literal and dynamic */}
<Link href="/about" />
<Link href={`/blog/${slug}`} />
<Link href={('/blog/' + slug) as Route} />
{/* TypeScript error if href is not a valid route */}
<Link href="/aboot" />
{/* Router: literal and dynamic strings are validated */}
<button onClick={() => router.push('/about')}>Push About</button>
<button onClick={() => router.replace(`/blog/${slug}`)}>
Replace Blog
</button>
<button onClick={() => router.prefetch('/contact')}>
Prefetch Contact
</button>
{/* For non-literal strings, cast to Route */}
<button onClick={() => router.push(('/blog/' + slug) as Route)}>
Push Non-literal Blog
</button>
</>
)
}
``` ```
The same applies for redirecting routes defined by middleware: The same applies for redirecting routes defined by middleware:
...@@ -184,13 +227,49 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) { ...@@ -184,13 +227,49 @@ function Card<T extends string>({ href }: { href: Route<T> | URL }) {
} }
``` ```
You can also type a simple data structure and iterate to render links:
```ts filename="components/nav-items.ts"
import type { Route } from 'next'
type NavItem<T extends string = string> = {
href: T
label: string
}
export const navItems: NavItem<Route>[] = [
{ href: '/', label: 'Home' },
{ href: '/about', label: 'About' },
{ href: '/blog', label: 'Blog' },
]
```
Then, map over the items to render `Link`s:
```tsx filename="components/nav.tsx"
import Link from 'next/link'
import { navItems } from './nav-items'
export function Nav() {
return (
<nav>
{navItems.map((item) => (
<Link key={item.href} href={item.href}>
{item.label}
</Link>
))}
</nav>
)
}
```
> **How does it work?** > **How does it work?**
> >
> When running `next dev` or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application (all valid routes as the `href` type of `Link`). This `.d.ts` file is included in `tsconfig.json` and the TypeScript compiler will check that `.d.ts` and provide feedback in your editor about invalid links. > When running `next dev` or `next build`, Next.js generates a hidden `.d.ts` file inside `.next` that contains information about all existing routes in your application (all valid routes as the `href` type of `Link`). This `.d.ts` file is included in `tsconfig.json` and the TypeScript compiler will check that `.d.ts` and provide feedback in your editor about invalid links.
### Type IntelliSense for Environment Variables ### Type IntelliSense for Environment Variables
During development, Next.js generates a `.d.ts` file in `.next/types` that contains information about the loaded environment variables for your editor's IntelliSense. If the same environment variable key is defined in multiple files, it is deduplicated according to the [Environment Variable Load Order](https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#environment-variable-load-order). During development, Next.js generates a `.d.ts` file in `.next/types` that contains information about the loaded environment variables for your editor's IntelliSense. If the same environment variable key is defined in multiple files, it is deduplicated according to the [Environment Variable Load Order](/docs/app/guides/environment-variables#environment-variable-load-order).
To opt-into this feature, `experimental.typedEnv` needs to be enabled and the project needs to be using TypeScript. To opt-into this feature, `experimental.typedEnv` needs to be enabled and the project needs to be using TypeScript.
...@@ -208,6 +287,8 @@ export default nextConfig ...@@ -208,6 +287,8 @@ export default nextConfig
> **Good to know**: Types are generated based on the environment variables loaded at development runtime, which excludes variables from `.env.production*` files by default. To include production-specific variables, run `next dev` with `NODE_ENV=production`. > **Good to know**: Types are generated based on the environment variables loaded at development runtime, which excludes variables from `.env.production*` files by default. To include production-specific variables, run `next dev` with `NODE_ENV=production`.
<AppOnly>
### With Async Server Components ### With Async Server Components
To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher. To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
...@@ -287,6 +368,64 @@ export default function MyApp({ Component, pageProps }: AppProps) { ...@@ -287,6 +368,64 @@ export default function MyApp({ Component, pageProps }: AppProps) {
Since `v10.2.1` Next.js supports [incremental type checking](https://www.typescriptlang.org/tsconfig#incremental) when enabled in your `tsconfig.json`, this can help speed up type checking in larger applications. Since `v10.2.1` Next.js supports [incremental type checking](https://www.typescriptlang.org/tsconfig#incremental) when enabled in your `tsconfig.json`, this can help speed up type checking in larger applications.
### Custom `tsconfig` path
In some cases, you might want to use a different TypeScript configuration for builds or tooling. To do that, set `typescript.tsconfigPath` in `next.config.ts` to point Next.js to another `tsconfig` file.
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
typescript: {
tsconfigPath: 'tsconfig.build.json',
},
}
export default nextConfig
```
For example, switch to a different config for production builds:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const isProd = process.env.NODE_ENV === 'production'
const nextConfig: NextConfig = {
typescript: {
tsconfigPath: isProd ? 'tsconfig.build.json' : 'tsconfig.json',
},
}
export default nextConfig
```
<details>
<summary>Why you might use a separate `tsconfig` for builds</summary>
You might need to relax checks in scenarios like monorepos, where the build also validates shared dependencies that don't match your project's standards, or when loosening checks in CI to continue delivering while migrating locally to stricter TypeScript settings (and still wanting your IDE to highlight misuse).
For example, if your project uses `useUnknownInCatchVariables` but some monorepo dependencies still assume `any`:
```json filename="tsconfig.build.json"
{
"extends": "./tsconfig.json",
"compilerOptions": {
"useUnknownInCatchVariables": false
}
}
```
This keeps your editor strict via `tsconfig.json` while allowing the production build to use relaxed settings.
</details>
> **Good to know**:
>
> - IDEs typically read `tsconfig.json` for diagnostics and IntelliSense, so you can still see IDE warnings while production builds use the alternate config. Mirror critical options if you want parity in the editor.
> - In development, only `tsconfig.json` is watched for changes. If you edit a different file name via `typescript.tsconfigPath`, restart the dev server to apply changes.
> - The configured file is used in `next dev`, `next build`, `next lint`, and `next typegen`.
### Disabling TypeScript errors in production ### Disabling TypeScript errors in production
Next.js fails your **production build** (`next build`) when TypeScript errors are present in your project. Next.js fails your **production build** (`next build`) when TypeScript errors are present in your project.
......
...@@ -46,7 +46,7 @@ The following commands are available: ...@@ -46,7 +46,7 @@ The following commands are available:
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available options. | | `-h, --help` | Show all available options. |
| `[directory]` | A directory in which to build the application. If not provided, current directory is used. | | `[directory]` | A directory in which to build the application. If not provided, current directory is used. |
| `--turbopack` | Starts development mode using [Turbopack](/docs/app/api-reference/turbopack). | | `--turbopack` | Starts development mode using [Turbopack](/docs/app/api-reference/turbopack). Also available as `--turbo`. |
| `-p` or `--port <port>` | Specify a port number on which to start the application. Default: 3000, env: PORT | | `-p` or `--port <port>` | Specify a port number on which to start the application. Default: 3000, env: PORT |
| `-H`or `--hostname <hostname>` | Specify a hostname on which to start the application. Useful for making the application available for other devices on the network. Default: 0.0.0.0 | | `-H`or `--hostname <hostname>` | Specify a hostname on which to start the application. Useful for making the application available for other devices on the network. Default: 0.0.0.0 |
| `--experimental-https` | Starts the server with HTTPS and generates a self-signed certificate. | | `--experimental-https` | Starts the server with HTTPS and generates a self-signed certificate. |
...@@ -79,6 +79,7 @@ The following options are available for the `next build` command: ...@@ -79,6 +79,7 @@ The following options are available for the `next build` command:
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available options. | | `-h, --help` | Show all available options. |
| `[directory]` | A directory on which to build the application. If not provided, the current directory will be used. | | `[directory]` | A directory on which to build the application. If not provided, the current directory will be used. |
| `--turbopack` | Build using [Turbopack](/docs/app/api-reference/turbopack) (beta). Also available as `--turbo`. |
| `-d` or `--debug` | Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown. | | `-d` or `--debug` | Enables a more verbose build output. With this flag enabled additional build output like rewrites, redirects, and headers will be shown. |
| | | |
| `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). | | `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). |
...@@ -214,6 +215,8 @@ next typegen ...@@ -214,6 +215,8 @@ next typegen
next typegen ./apps/web next typegen ./apps/web
``` ```
> **Good to know**: `next typegen` loads your Next.js config (`next.config.js`, `next.config.mjs`, or `next.config.ts`) using the production build phase. Ensure any required environment variables and dependencies are available so the config can load correctly.
## Examples ## Examples
### Debugging prerender errors ### Debugging prerender errors
......
...@@ -30,7 +30,7 @@ To enable Turbopack in your Next.js project, add the `--turbopack` flag to the ` ...@@ -30,7 +30,7 @@ To enable Turbopack in your Next.js project, add the `--turbopack` flag to the `
} }
``` ```
Currently, Turbopack for `dev` is stable, while `build` is in alpha. We are actively working on production support as Turbopack moves closer to stability. Currently, Turbopack for `dev` is stable, while `build` is in beta. We are actively working on production support as Turbopack moves closer to stability.
## Supported features ## Supported features
......
...@@ -13,7 +13,7 @@ description: Next.js has built-in support for internationalized routing and lang ...@@ -13,7 +13,7 @@ description: Next.js has built-in support for internationalized routing and lang
Next.js has built-in support for internationalized ([i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization#Naming)) routing since `v10.0.0`. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing. Next.js has built-in support for internationalized ([i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization#Naming)) routing since `v10.0.0`. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing.
The i18n routing support is currently meant to complement existing i18n library solutions like [`react-intl`](https://formatjs.io/docs/getting-started/installation), [`react-i18next`](https://react.i18next.com/), [`lingui`](https://lingui.dev/), [`rosetta`](https://github.com/lukeed/rosetta), [`next-intl`](https://github.com/amannn/next-intl), [`next-translate`](https://github.com/aralroca/next-translate), [`next-multilingual`](https://github.com/Avansai/next-multilingual), [`tolgee`](https://tolgee.io/integrations/next), [`paraglide-next`](https://inlang.com/m/osslbuzt/paraglide-next-i18n), [`next-intlayer`](https://intlayer.org/doc/environment/nextjs) and others by streamlining the routes and locale parsing. The i18n routing support is currently meant to complement existing i18n library solutions like [`react-intl`](https://formatjs.io/docs/getting-started/installation), [`react-i18next`](https://react.i18next.com/), [`lingui`](https://lingui.dev/), [`rosetta`](https://github.com/lukeed/rosetta), [`next-intl`](https://github.com/amannn/next-intl), [`next-translate`](https://github.com/aralroca/next-translate), [`next-multilingual`](https://github.com/Avansai/next-multilingual), [`tolgee`](https://tolgee.io/integrations/next), [`paraglide-next`](https://inlang.com/m/osslbuzt/paraglide-next-i18n), [`next-intlayer`](https://intlayer.org/doc/environment/nextjs/next-with-page-router) and others by streamlining the routes and locale parsing.
## Getting started ## Getting started
......
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