Migration from Next 12 to Next 13
Next.js came out with their latest version Next.js 13 and I migrated to Next 13 from 12 and this is how I did it.
Before getting into how, it is important for me to list the upgrades that came along with 13.
-
The new next/image - The new Next future image allows you to render images without layout shifts and load images on-demand for increased performance
The new Image component:
- Ships less client-side JavaScript.
- Easier to style and configure.
- More accessible requiring alt tags by default.
- Aligns with the Web platform Faster because native lazy loading doesn't require hydration.
-
The next/link child can no longer be
<a>. Add thelegacyBehaviorprop to use the legacy behavior or remove the<a>to upgrade. -
The next/font Next.js 13 introduces a brand new font system that:
- Automatically optimizes your fonts, including custom fonts.
- Removes external network requests for improved privacy and performance.
- Built-in automatic self-hosting for any font file.
- Zero layout shift automatically using the CSS size-adjust property.
-
Turbopack (alpha) Up to 700x faster Rust-based Webpack replacement.
How Did I Migrate?
First I upgraded the Next, React, ReactDOM and eslint versions in my package.json file. using this command
npm i next@latest react@latest react-dom@latest eslint-config-next@latest
after having done that I saw that there were majorly two things that were broken. The images and the links.
List of Errors
Invalid Link issue
Error: Invalid `<Link>` with `<a>` child.
Please remove `<a>` or use `<Link legacyBehavior>`.
Solution: Use below codemod.
npx @next/codemod new-link
Broken Image tag issue.
Error: Do not use <img>. Use Image from 'next/image' instead. - Next.js using html tag <img />
Solution: Use below codemod.
npx @next/codemod next-image-to-legacy-image ./pages
Having done this the next set of errors I faced were my dependent packages that were not compatible with the new react version
In order to support Next 13, The minimum React version has been bumped from 17.0.2 to 18.2.0.
Hydration Errors
What is Hydration? While rendering the application, there is a difference between the React tree that was pre-rendered (SSR/SSG) and the React tree that rendered during the first render in the Browser.This first render is called Hydration
This can cause the React tree to be out of sync with the DOM and result in unexpected content/attributes being present.
Error:Hydration failed because the initial UI does not match what was rendered on the server
Solution:
- By checking in any case if there is any lower precedence tag wrapped around a higher precedence tag.Such as div inside p
- By not having nested next/link elements.
- Hydration fails when children elements are dangerously set inner HTML.