File size: 13,168 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
---
title: Codemods
description: Use codemods to upgrade your Next.js codebase when new features are released.
---
Codemods are transformations that run on your codebase programmatically. This allows a large number of changes to be programmatically applied without having to manually go through every file.
Next.js provides Codemod transformations to help upgrade your Next.js codebase when an API is updated or deprecated.
## Usage
In your terminal, navigate (`cd`) into your project's folder, then run:
```bash filename="Terminal"
npx @next/codemod <transform> <path>
```
Replacing `<transform>` and `<path>` with appropriate values.
- `transform` - name of transform
- `path` - files or directory to transform
- `--dry` Do a dry-run, no code will be edited
- `--print` Prints the changed output for comparison
## Codemods
### 15.0
#### Transform App Router Route Segment Config `runtime` value from `experimental-edge` to `edge`
##### `app-dir-runtime-config-experimental-edge`
> **Note**: This codemod is App Router specific.
```bash filename="Terminal"
npx @next/codemod@latest app-dir-runtime-config-experimental-edge .
```
This codemod transforms [Route Segment Config `runtime`](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#runtime) value `experimental-edge` to `edge`.
For example:
```ts
export const runtime = 'experimental-edge'
```
Transforms into:
```ts
export const runtime = 'edge'
```
#### Migrate to async Dynamic APIs
APIs that opted into dynamic rendering that previously supported synchronous access are now asynchronous. You can read more about this breaking change in the [upgrade guide](/docs/app/guides/upgrading/version-15).
##### `next-async-request-api`
```bash filename="Terminal"
npx @next/codemod@latest next-async-request-api .
```
This codemod will transform dynamic APIs (`cookies()`, `headers()` and `draftMode()` from `next/headers`) that are now asynchronous to be properly awaited or wrapped with `React.use()` if applicable.
When an automatic migration isn't possible, the codemod will either add a typecast (if a TypeScript file) or a comment to inform the user that it needs to be manually reviewed & updated.
For example:
```tsx
import { cookies, headers } from 'next/headers'
const token = cookies().get('token')
function useToken() {
const token = cookies().get('token')
return token
}
export default function Page() {
const name = cookies().get('name')
}
function getHeader() {
return headers().get('x-foo')
}
```
Transforms into:
```tsx
import { use } from 'react'
import {
cookies,
headers,
type UnsafeUnwrappedCookies,
type UnsafeUnwrappedHeaders,
} from 'next/headers'
const token = (cookies() as unknown as UnsafeUnwrappedCookies).get('token')
function useToken() {
const token = use(cookies()).get('token')
return token
}
export default async function Page() {
const name = (await cookies()).get('name')
}
function getHeader() {
return (headers() as unknown as UnsafeUnwrappedHeaders).get('x-foo')
}
```
When we detect property access on the `params` or `searchParams` props in the page / route entries (`page.js`, `layout.js`, `route.js`, or `default.js`) or the `generateMetadata` / `generateViewport` APIs,
it will attempt to transform the callsite from a sync to an async function, and await the property access. If it can't be made async (such as with a Client Component), it will use `React.use` to unwrap the promise .
For example:
```tsx
// page.tsx
export default function Page({
params,
searchParams,
}: {
params: { slug: string }
searchParams: { [key: string]: string | string[] | undefined }
}) {
const { value } = searchParams
if (value === 'foo') {
// ...
}
}
export function generateMetadata({ params }: { params: { slug: string } }) {
const { slug } = params
return {
title: `My Page - ${slug}`,
}
}
```
Transforms into:
```tsx
// page.tsx
export default async function Page(props: {
params: Promise<{ slug: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
const searchParams = await props.searchParams
const { value } = searchParams
if (value === 'foo') {
// ...
}
}
export async function generateMetadata(props: {
params: Promise<{ slug: string }>
}) {
const params = await props.params
const { slug } = params
return {
title: `My Page - ${slug}`,
}
}
```
> **Good to know:** When this codemod identifies a spot that might require manual intervention, but we aren't able to determine the exact fix, it will add a comment or typecast to the code to inform the user that it needs to be manually updated. These comments are prefixed with **@next/codemod**, and typecasts are prefixed with `UnsafeUnwrapped`.
> Your build will error until these comments are explicitly removed. [Read more](/docs/messages/sync-dynamic-apis).
#### Replace `geo` and `ip` properties of `NextRequest` with `@vercel/functions`
##### `next-request-geo-ip`
```bash filename="Terminal"
npx @next/codemod@latest next-request-geo-ip .
```
This codemod installs `@vercel/functions` and transforms `geo` and `ip` properties of `NextRequest` with corresponding `@vercel/functions` features.
For example:
```ts
import type { NextRequest } from 'next/server'
export function GET(req: NextRequest) {
const { geo, ip } = req
}
```
Transforms into:
```ts
import type { NextRequest } from 'next/server'
import { geolocation, ipAddress } from '@vercel/functions'
export function GET(req: NextRequest) {
const geo = geolocation(req)
const ip = ipAddress(req)
}
```
### 14.0
#### Migrate `ImageResponse` imports
##### `next-og-import`
```bash filename="Terminal"
npx @next/codemod@latest next-og-import .
```
This codemod moves transforms imports from `next/server` to `next/og` for usage of [Dynamic OG Image Generation](/docs/app/getting-started/metadata-and-og-images#generated-open-graph-images).
For example:
```js
import { ImageResponse } from 'next/server'
```
Transforms into:
```js
import { ImageResponse } from 'next/og'
```
#### Use `viewport` export
##### `metadata-to-viewport-export`
```bash filename="Terminal"
npx @next/codemod@latest metadata-to-viewport-export .
```
This codemod migrates certain viewport metadata to `viewport` export.
For example:
```js
export const metadata = {
title: 'My App',
themeColor: 'dark',
viewport: {
width: 1,
},
}
```
Transforms into:
```js
export const metadata = {
title: 'My App',
}
export const viewport = {
width: 1,
themeColor: 'dark',
}
```
### 13.2
#### Use Built-in Font
##### `built-in-next-font`
```bash filename="Terminal"
npx @next/codemod@latest built-in-next-font .
```
This codemod uninstalls the `@next/font` package and transforms `@next/font` imports into the built-in `next/font`.
For example:
```js
import { Inter } from '@next/font/google'
```
Transforms into:
```js
import { Inter } from 'next/font/google'
```
### 13.0
#### Rename Next Image Imports
##### `next-image-to-legacy-image`
```bash filename="Terminal"
npx @next/codemod@latest next-image-to-legacy-image .
```
Safely renames `next/image` imports in existing Next.js 10, 11, or 12 applications to `next/legacy/image` in Next.js 13. Also renames `next/future/image` to `next/image`.
For example:
```jsx filename="pages/index.js"
import Image1 from 'next/image'
import Image2 from 'next/future/image'
export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}
```
Transforms into:
```jsx filename="pages/index.js"
// 'next/image' becomes 'next/legacy/image'
import Image1 from 'next/legacy/image'
// 'next/future/image' becomes 'next/image'
import Image2 from 'next/image'
export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}
```
#### Migrate to the New Image Component
##### `next-image-experimental`
```bash filename="Terminal"
npx @next/codemod@latest next-image-experimental .
```
Dangerously migrates from `next/legacy/image` to the new `next/image` by adding inline styles and removing unused props.
- Removes `layout` prop and adds `style`.
- Removes `objectFit` prop and adds `style`.
- Removes `objectPosition` prop and adds `style`.
- Removes `lazyBoundary` prop.
- Removes `lazyRoot` prop.
#### Remove `<a>` Tags From Link Components
##### `new-link`
```bash filename="Terminal"
npx @next/codemod@latest new-link .
```
<AppOnly>
Remove `<a>` tags inside [Link Components](/docs/app/api-reference/components/link), or add a `legacyBehavior` prop to Links that cannot be auto-fixed.
</AppOnly>
<PagesOnly>
Remove `<a>` tags inside [Link Components](/docs/pages/api-reference/components/link), or add a `legacyBehavior` prop to Links that cannot be auto-fixed.
</PagesOnly>
For example:
```jsx
<Link href="/about">
<a>About</a>
</Link>
// transforms into
<Link href="/about">
About
</Link>
<Link href="/about">
<a onClick={() => console.log('clicked')}>About</a>
</Link>
// transforms into
<Link href="/about" onClick={() => console.log('clicked')}>
About
</Link>
```
In cases where auto-fixing can't be applied, the `legacyBehavior` prop is added. This allows your app to keep functioning using the old behavior for that particular link.
```jsx
const Component = () => <a>About</a>
<Link href="/about">
<Component />
</Link>
// becomes
<Link href="/about" legacyBehavior>
<Component />
</Link>
```
### 11
#### Migrate from CRA
##### `cra-to-next`
```bash filename="Terminal"
npx @next/codemod cra-to-next
```
Migrates a Create React App project to Next.js; creating a Pages Router and necessary config to match behavior. Client-side only rendering is leveraged initially to prevent breaking compatibility due to `window` usage during SSR and can be enabled seamlessly to allow the gradual adoption of Next.js specific features.
Please share any feedback related to this transform [in this discussion](https://github.com/vercel/next.js/discussions/25858).
### 10
#### Add React imports
##### `add-missing-react-import`
```bash filename="Terminal"
npx @next/codemod add-missing-react-import
```
Transforms files that do not import `React` to include the import in order for the new [React JSX transform](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) to work.
For example:
```jsx filename="my-component.js"
export default class Home extends React.Component {
render() {
return <div>Hello World</div>
}
}
```
Transforms into:
```jsx filename="my-component.js"
import React from 'react'
export default class Home extends React.Component {
render() {
return <div>Hello World</div>
}
}
```
### 9
#### Transform Anonymous Components into Named Components
##### `name-default-component`
```bash filename="Terminal"
npx @next/codemod name-default-component
```
**Versions 9 and above.**
Transforms anonymous components into named components to make sure they work with [Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh).
For example:
```jsx filename="my-component.js"
export default function () {
return <div>Hello World</div>
}
```
Transforms into:
```jsx filename="my-component.js"
export default function MyComponent() {
return <div>Hello World</div>
}
```
The component will have a camel-cased name based on the name of the file, and it also works with arrow functions.
### 8
#### Transform AMP HOC into page config
##### `withamp-to-config`
```bash filename="Terminal"
npx @next/codemod withamp-to-config
```
Transforms the `withAmp` HOC into Next.js 9 page configuration.
For example:
```js
// Before
import { withAmp } from 'next/amp'
function Home() {
return <h1>My AMP Page</h1>
}
export default withAmp(Home)
```
```js
// After
export default function Home() {
return <h1>My AMP Page</h1>
}
export const config = {
amp: true,
}
```
### 6
#### Use `withRouter`
##### `url-to-withrouter`
```bash filename="Terminal"
npx @next/codemod url-to-withrouter
```
Transforms the deprecated automatically injected `url` property on top level pages to using `withRouter` and the `router` property it injects. Read more here: [https://nextjs.org/docs/messages/url-deprecated](/docs/messages/url-deprecated)
For example:
```js filename="From"
import React from 'react'
export default class extends React.Component {
render() {
const { pathname } = this.props.url
return <div>Current pathname: {pathname}</div>
}
}
```
```js filename="To"
import React from 'react'
import { withRouter } from 'next/router'
export default withRouter(
class extends React.Component {
render() {
const { pathname } = this.props.router
return <div>Current pathname: {pathname}</div>
}
}
)
```
This is one case. All the cases that are transformed (and tested) can be found in the [`__testfixtures__` directory](https://github.com/vercel/next.js/tree/canary/packages/next-codemod/transforms/__testfixtures__/url-to-withrouter).
|