next-navigation-migrator
v1.0.3
Published
A codemod to migrate from Next.js Pages Router (next/router) to App Router (next/navigation)
Maintainers
Readme
Next.js Navigation Migrator
A powerful codemod library to migrate your Next.js application from the Pages Router (next/router) to the App Router (next/navigation). This tool intelligently transforms your components to use the new router APIs with minimal manual intervention.
Features
- 🔄 Automatically replaces
next/routerimports with appropriatenext/navigationhooks - 🧩 Transforms router properties like
queryandpathnameto their Navigation API equivalents - 🔍 Handles different query parameter patterns including array parameters
- 🧹 Removes unnecessary router declarations when only query/pathname are used
- 📝 Adds useful code comments for manual migration steps
- 🔒 Automatically adds the
'use client'directive where needed - 🔄 Works with both JavaScript and TypeScript codebases
Installation
Global Installation (Recommended)
npm install -g next-navigation-migratorLocal Installation
npm install --save-dev next-navigation-migratorUsage
Command Line Interface
Run the migration on your entire Next.js project:
# If installed globally
next-navigation-migrator ./path/to/your/project
# If installed locally
npx next-navigation-migrator ./path/to/your/projectWhat This Codemod Does
Based on the official Next.js migration guide and common patterns, this codemod handles the following key migration points:
Import Path Changes
- Changes imports from
next/routertonext/navigation - Adds appropriate imports for additional hooks when needed (
useSearchParams,usePathname) - Handles both named and default imports (or an empty import that’s missing required hooks)
Router Property Transformations
router.pathname→usePathname()router.query→useSearchParams()router.query.param→useSearchParams().get('param')router.query.arrayParam→Array.from(useSearchParams().getAll('arrayParam'))router.asPath→usePathname()(with comments on query differences)- Destructuring like
const { query } = router→const query = useSearchParams() - Object destructuring like
const { id } = router.query→const id = useSearchParams().get('id')
Optimization
- Removes unnecessary
const router = useRouter()declarations when only used for query/pathname - Updates
useEffectdependencies fromquery.paramtosearchParams
Router Methods
- Updates
router.push()androuter.replace()to remove unsupported options (such asshallow) and extra arguments, retaining only supported options such asscroll - Adds comments for manual review of router method transformations
License
This project is licensed under the MIT License.
