18 August 2023
Next.js v13 has a number of new features and improvements. However, there are also some breaking changes that you should be aware of when you plan to migrate to the new /app directory. In this list, I will share the pitfalls that I have experienced myself that I think everyone planning to upgrade their app should be aware of. Please note that your app will continue to work after upgrading the package. You will only encounter these pitfalls if you plan to migrate to the /app directory.
So let's start with this basic hook useRouter. Unlike in the /pages directory, useRouter in the /app directory should be imported from next/navigation.
The new useRouter is now more exclusive with its purpose - to route. Getting of the URL params is not possible anymore with this hook. You will need to use a new hook which is also from next/navigation - useSearchParams.
The new usePathname is the new hook for getting the current pathname and also can be imported from next/navigation.
/pages directory
/app directory
The useRouter hook from next/router is still available, but it can only be used in the /pages directory. It is not available in the new /app directory.
If your app is using the routeChangeStart and routeChangeComplete and the other route event listeners then you probably gonna have to recreate these on your own in the /app directory.
In the Next.js documentation, they suggest using the new hooks to replicate these, but in my experience, it is not enough to replace the router events.
Below is how I replicated the router events:
Inspired by this repo: nextjs13-appdir-router-events
In Next.js v13, all files under the new /app directory are server files by default. This also applies if you import your old code from the /pages directory.
However, you can still reuse your old components that use client-side hooks, such as useState and useEffect, by using the new use client directive.
As stated in their official documentation,
"The 'use client' directive is a convention to declare a boundary between a Server and Client Component module graph."
(Next.js Documentation, 2023)
I would recommend reading their official documentation about this. Understanding the React Essential is a good way to start migrating your site.
That's it for now!
Migrating your Next.js app from /pages directory to /app directory in the new version can be a hassle, especially if you plan to reuse old code from the old directory. By following the tips above, you can help to ensure that your migration to this new version of Next.js is smoother.
Learn more