Introduction to Smooth Upgrades with @next-codemod CLI in Next.js 15

Upgrading to new versions of Next.js can be daunting, especially when major updates bring significant changes. With Next.js 15, developers can leverage the @next/codemod CLI, a tool designed to automate code transformations, making the transition seamless and efficient. This tutorial will walk you through using the @next/codemod CLI to upgrade your project to Next.js 15, covering everything from installation to common FAQs.

What is @next/codemod CLI?

@next/codemod CLI is a command-line tool that automates code upgrades for Next.js projects. When a new version of Next.js is released, it helps developers by identifying deprecated APIs, outdated configurations, and other changes needed to align the codebase with the latest version. Here’s what makes @next/codemod unique:

  • Automates code modifications to adapt to breaking changes.
  • Reduces manual adjustments, saving time and minimizing human error.
  • Supports stable and canary releases, allowing developers to adopt the latest features quickly.

Sequence Diagram

πŸ“¦ Project CodebaseπŸ› οΈ Codemod CLIπŸ‘©β€πŸ’» DeveloperπŸ“¦ Project CodebaseπŸ› οΈ Codemod CLIπŸ‘©β€πŸ’» DeveloperInstall @next/codemod CLIβœ… Confirms installationRun upgrade commandπŸ” Analyze codebase for deprecated componentsπŸ“‹ List deprecated components & configsSuggests codemods & dry-run optionsSelect transformations & runπŸ”„ Apply codemodsβœ”οΈ Confirms applied changesπŸ“ Print logs of changesπŸ§ͺ Review & test compatibilityπŸŽ‰ Upgrade complete

Step-by-Step Guide to Using @next/codemod CLI

Note - Make sure you create a separate GIT branch for testing it.

1. Install the CLI

To get started, install the CLI using the following command:

npx @next/codemod@canary
  • The canary tag ensures that you are using the latest version of the codemod, including the most recent bug fixes and enhancements.

2. Run the Upgrade Command

Run the upgrade command to update your codebase:

npx @next/codemod@canary upgrade latest

This command checks your Next.js project and suggests changes based on the latest stable version of Next.js 15.

3. Codemod Selection

The CLI will display a list of available codemods that target specific changes, such as:

  • Updating imports for new APIs.
  • Refactoring deprecated server components.
  • Modifying middleware or static generation configurations.

Select the required codemods for your project and confirm to apply the changes.

4. Review the Changes

After applying codemods, it’s crucial to review the modified files:

  • Check for correct transformations and ensure there are no unintended changes.
  • The CLI provides a detailed log of changes for easier review.

5. Testing and Debugging

  • After applying codemods, run your application to ensure everything works smoothly.
  • Test different functionalities, such as server-side rendering, API routes, and client-side navigation to catch potential issues.
  • Use the logs generated by the codemod to identify any specific errors or warnings.

6. Handle Manual Adjustments

While codemods handle a large portion of the upgrade process, some areas might require manual adjustments:

  • Custom APIs or legacy configurations might not be covered by automated scripts.
  • Use the Next.js 15 migration guide to handle such cases manually.

Here’s a more accurate and meaningful example that demonstrates a codemod transformation for upgrading from Next.js 14 to Next.js 15:

Example: Upgrading Dynamic APIs in Next.js 14 to Next.js 15

Let’s assume you have a Next.js 14 app using dynamic API calls like cookies() and headers() synchronously, which need to be updated to asynchronous calls in Next.js 15.

Before Codemod

import { cookies, headers } from 'next/headers';

export async function getServerSideProps() {
  const token = cookies().get('token');
  const userAgent = headers().get('User-Agent');

  return {
    props: {
      token,
      userAgent,
    },
  };
}

After Codemod

import { cookies, headers } from 'next/headers';

export async function getServerSideProps() {
  const token = (await cookies()).get('token');
  const userAgent = (await headers()).get('User-Agent');

  return {
    props: {
      token,
      userAgent,
    },
  };
}
  • Before Codemod: The original code calls cookies() and headers() synchronously, which is deprecated in Next.js 15.
  • After Codemod: The updated code wraps cookies() and headers() with await, making them asynchronous and compatible with the new API requirements.

Key Changes

πŸš€ Route Segment Config

Next.js 14Used export const runtime = 'experimental-edge' to indicate experimental Edge runtime support.
Next.js 15Codemods replace it with runtime = 'edge', marking stable Edge runtime support.

πŸͺ Dynamic APIs

Next.js 14Dynamic APIs like cookies() and headers() were synchronous, leading to blocking behavior during rendering.
Next.js 15Codemods make these APIs asynchronous, ensuring non-blocking operations and better performance.

⚑ Dynamic Imports

Next.js 14Direct access to named exports using next/dynamic could cause compatibility issues with React.lazy.
Next.js 15Codemods wrap named exports in an object with a default property, improving compatibility with React.lazy.

πŸ”„ Middleware

Next.js 14Middleware had partial support for Edge runtimes, making them less efficient for scaling.
Next.js 15Codemods update middleware to fully support Edge runtimes, improving scalability and performance.

πŸ“¦ Named Exports in Dynamic Imports

Next.js 14Dynamic imports could access named exports directly, causing issues with compatibility.
Next.js 15Codemods wrap named exports with a default property, improving compatibility with React.lazy.

πŸ“ Geo & IP Properties

Before import type { NextRequest } from 'next/server';

export function GET(req: NextRequest) {
  const { geo, ip } = req;
}
After 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);
}

🎨 OG Image Generation

Next.js 14Used ImageResponse from next/server for OG image generation, which was more complex.
Next.js 15Codemods update imports to use next/og for simpler OG image generation.

πŸ” Viewport Metadata

Next.js 14Viewport settings were part of the metadata object, limiting customization.
Next.js 15Codemods separate the viewport export, improving customization capabilities.

πŸ”  Font Handling

Next.js 13.2Used the @next/font package, requiring manual import and configuration.
Next.js 15Codemods transition to built-in support for next/font, simplifying integration.
BEFORE Next.js 14Did not require wrapping content inside <a> tags. Wrapping was optional to pass attributes like target or className.
Next.js 15Codemods remove redundant <a> tags or add the legacyBehavior prop for backward compatibility.

FAQs

Q: What does the @next/codemod CLI do during a Next.js upgrade?

The @next/codemod CLI is a tool built to make upgrading Next.js projects easier. It scans the codebase to identify outdated components, deprecated APIs, and old configurations. The tool automatically modifies the code to match the latest Next.js standards, which speeds up the process and reduces manual effort. It’s particularly useful during major updates, like the shift to Next.js 15, which introduces breaking changes. This ensures that your project remains aligned with new features and updates.

Q: How does the codemod handle custom implementations or APIs?

The codemod mainly focuses on transforming standard Next.js components and APIs. When dealing with custom APIs or unique configurations, the tool may not be able to handle them fully. In such cases, it adds comments indicating where manual review is needed. For example, if your project includes custom middleware, the codemod will flag it for manual adjustment, prompting you to review and update those parts according to the Next.js 15 migration guidelines.

Q: Can I use the codemod CLI for both minor and major upgrades?

Yes, the codemod is effective for both minor and major upgrades. While it’s more beneficial for major transitions like from Next.js 14 to 15β€”where breaking changes are commonβ€”it can also handle minor version upgrades. It automates changes such as updating imports, function signatures, or configuration adjustments that come with minor releases. Using the codemod for minor updates ensures consistency across your codebase, reducing potential errors.

Q: Is the codemod CLI suitable for large-scale projects?

Yes, the codemod is built to work efficiently on large codebases. It scans multiple files and applies transformations consistently. However, for safety, it's recommended to create a backup of your project or use a separate Git branch before running the tool. This approach allows you to easily revert changes if needed. After applying codemods, thorough testing is necessary to confirm the changes are compatible and don’t break existing functionality.

Q: How should I prepare my project before using the codemod CLI?

Before running the @next/codemod CLI:

  • Create a backup or a separate branch for safety.
  • Use the dry-run option (--dry) to preview the proposed changes without modifying files.
  • Check for custom APIs or third-party libraries, as these might require manual updates.
  • Use the print option (--print) to display the transformations for comparison before applying them to the codebase.

Q: What happens if the codemod cannot transform some parts of the code?

If the codemod encounters code that it cannot change automaticallyβ€”like unusual component setups or specific custom APIsβ€”it will add comments to guide manual adjustments. These comments explain why the transformation wasn’t possible and suggest how to update that part of the code. You should carefully review these comments, refer to Next.js documentation, and manually make the necessary changes to ensure compatibility with Next.js 15.

Q: How can I confirm that the codemod worked correctly?

To ensure the codemod worked properly, review the logs generated after applying it. These logs provide details about the changes made, including updates to imports, components, and configurations. After reviewing the logs, run your test suite to catch any issues and ensure that everything functions as expected. It’s also advisable to manually inspect critical areas of the application, like API routes and dynamic imports, to confirm the upgrade is successful.

Q: Can I undo changes made by the codemod CLI if needed?

Yes, you can revert changes by using version control, especially if you performed the upgrade in a separate branch. If specific changes need to be undone, you can review the logs to identify the modified parts and manually revert them.

Q: What are the most common issues when using @next/codemod CLI?

Common issues include:

  • Skipping tests after applying the codemod, which can lead to undetected errors.
  • Not using the dry-run mode before applying changes, which can result in unintended modifications.
  • Assuming all code changes are correct; always review and manually adjust any flagged custom components or APIs.

Q: How does @next/codemod CLI handle TypeScript?

The codemod supports TypeScript transformations by adding type hints and refactoring code to align with Next.js 15’s requirements. For complex TypeScript structures, the codemod might add comments or hints to indicate where manual updates are needed. It ensures that updated code remains compatible with TypeScript standards while aligning with the latest Next.js features.

Q: What specific changes does the codemod make for Next.js 15?

The codemod in Next.js 15 handles:

  • Transition from synchronous to asynchronous APIs.
  • Updating configurations from experimental-edge to edge for the App Router.
  • Adjustments for React 19 compatibility.
  • Improved static vs. dynamic rendering logic, supporting Partial Prerendering (PPR)【42†source】【43†source】【45†source】.

Conclusion

The @next/codemod CLI is an essential tool for upgrading Next.js projects efficiently. By automating code transformations, it ensures a smooth transition to the latest versions while minimizing errors. Follow the step-by-step guide and test your application thoroughly to enjoy the new features and improvements introduced in Next.js 15.

Clap here if you liked the blog