🚨

Nextjs / Vercel / React related errors and solutions

Anh-Thi Dinh
draft
⚠️
These are my quick and dirty notes about the issues I encountered when developing sites with Next.js. They’re in English / Vietnamese / French.
Best practice with Vercel
  • With free account, you should host each project in a different account to get the most free tier data.
Use emoji as favicon
Remove all other related files and create src/app/icon.tsx
Strange webpack warning [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item
Install yarn add -D postcss-reporter and then add to postcss.config.js
1module.exports = {
2  plugins: {
3    // ...
4    // 👇 Make sure it's the last one
5    'postcss-reporter': { clearReportedMessages: true }
6  }
7}
ReferenceError: window is not defined
Chỗ nào có window thì phải để trong component client (’use client’) và dùng useEffect.
Dùng next/dynamic thì sẽ không còn lỗi gì. Check this SO.
Nếu gặp tình trạng anchor link (# after the url) đột nhiên biến mất khi rê chuột vào navigation bar (có chứa Link)
Lý do là chức năng prefetch của Link. Chỉ cần thêm prefetch={false} vào trong Link là fix được lỗi này!
Module not found: Error can't resolve 'child_process', how to fix?
You can use child_process in your getStaticProps and getServerSideProps.
Có thể dùng mấy hàm của Nodejs nhưng ko đặt trong getStatic… mà để bên ngoài???
Image is missing required "width" (or "height") property.
Instead of using relative like `../public/abc.png`, use `/abc.png`. Everything in `public/` can be accessed via `/`. Morevover, use "with" and "height" for `Image`.
React Hydration Error: Error: Hydration failed because the initial UI does not match what was rendered on the server. (read more)
Có thể là <a> cannot appear as a descendant of <a>. hoặc div inside p. Có thể lần đầu yarn dev sẽ không thấy lỗi cụ thể này mà là một lỗi chung chung. Khi ấy (yarn dev đang chạy) chỉ cần cancel rùi yarn dev lại là nó hiển thị ra cái lỗi rõ ràng hơn.
🚨 Error: HTTPError: Response code 417 (Expectation Failed) when upload image to imgur.
Reason: wrong image format!
Text content does not match server-rendered HTML. (Error: Minified React error #418 or #425)
Request to Notion API failed with status: 502 khi build hoặc khi dùng yarn dev mà load 1 trang nào đó → chỉ cần thử lại là ok!
yarn clean xong yarn build lại!
Warning: data for page "/[postSlug]" (path "/17-phuong-trinh-lam-thay-doi-the-gioi/") is 163 kB which exceeds the threshold of 128 kB, this amount of data can reduce performance.
Dùng dynamic component → xem thử block-render.tsx như 1 ví dụ!
Request to Notion API has timed out
Thử rebuild lại. Nếu bị trên Notion thì thử deploy lại ngay trong chỗ deployment luôn!
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Tại vì mình định nghĩa 1 component rời (eg. <Comp ...>), xong nhét nó vào giữa <Tippy> → phải có React.forwardRef mới được. Còn nếu mình để nguyên xi cái định nghĩa của Comp trong Tippy thì không có lỗi!
Nếu dùng mấy cái component của react-icons vẫn bị.
Solution: nếu vẫn muốn dùng component inside (hoặc dùng react-icons) thì co thể bao quanh cái component bằng 1 HTML tag khác là ok!
Type 'KeyboardEvent' is not generic.ts
Change from KeyboardEvent<HTMLInputElement> to React.KeyboardEvent<HTMLInputElement>
Extra attributes from the server: cz-shortcut-listen
Add suppressHydrationWarning={true} to the <body tag.
Something went wrong installing the "sharp" module OR Cannot find module 'relative "../build/Release/sharp-" <dynamic> ".node"’
Tại dùng --turbo khi yarn dev, bỏ cái này đi là không lỗi nữa! ← Lỗi install sharp trên Mac M1.
→ do đã upgrade plaiceholder lên bản 3.0.0 nên bị → đọc cái này để migrate!
TypeError: Super expression must either be null or a function
Có thể mình đã import {name} thay vì name từ một file nào đó khi file đó export default cái name!
Cũng có thể thiếu 'use client' ở 1 số component nào đó! ← yep! bên trong BlockCode, for example!

Một lần khác để cái react component bên trong 1 file utils.tsx trong khi file đó nên là utils.ts còn react component kia thì nên ở file .tsx. Khi import 1 method trong cái utils.tsx, nó bị lỗi ngay cái react component!
Module not found: Can't resolve 'fs' ← Lỗi xuất hiện khi cài và sử dụng plaiceholder
Chỉ cần đổi chỗ mấy hàm khi call sau cho hợp lý là ok!
Error: Input buffer has corrupt header: magickload_buffer: Magick: must specify image size
yarn clean sau đó yarn dev hoặc yarn build là ok!
Prop className did not match….
Just remove .next folder and restart yarn dev
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './server.edge' is not defined by "exports”
Cái này là do sử dụng esmExternals: 'loose' trong next.config.mjs. Lý do hiện tại đang dùng là vì đang sử dụng package react-medium-image-zoom. Xem thêm. Tạm thời chịu thấy lỗi này xuất hiện thui, chưa thấy tác hại gì!
❓ Vẫn có trường hợp ko dùng esmExternals: 'loose' nhưng vẫn bị!
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Good to read: https://bobbyhadz.com/blog/react-element-type-is-invalid-expected-string-but-got ← khá đầy đủ, có thể ko chính xác cái nó đang warning nhưng tìm hiểu sâu hơn bên trong có thể bắt gặp!
Nó báo lỗi ở BadgeSocial nhưng thật ra lỗi đến từ cái Tippy returned của cái badge.
Một lần khác lỗi ở block video, vẫn chưa hiểu tại sao nó bị dù react-youtube đã export đúng ← quyết định remove lib này và làm cái builtin
Có thể ko hợp version giữa nextjs bên v6 và notion-nextjs-lib? (13.4.19 vs 13.4.14) ← ko phải
  • Có thể do version mới bị, cái 13.4.4 ko bị! ← CHÍNH XÁC!!!, 13.4.12 vẫn bị ← 13.4.7 ko bị
Error: Element type is invalid. Received a promise that resolves to: [object Promise]. Lazy element type must resolve to a class or function.
Lạ là trên browser nó hiển thị cái này nhưng trên terminal nó hiển thị cái lỗi “Uncaught Error: Element type is invalid: expected a string”.
Cách fix: Thay vì import 1 component trực tiếp thì dùng dynamic. Check component ObjectIdComponent như một ví dụ. Nếu component này import ObjectIdGenerator trực tiếp sẽ gây ra lỗi trên, còn nếu dùng dynamic thì không bị lỗi nữa!
Warning: Expected server HTML to contain a matching <div> in <article>.
May be related: Warning: Expected server HTML to contain a matching <div> in <div> due to State
Code that is only supposed to run in the browser should be executed inside useEffect. That's required because the first render should match the initial render of the server. If you manipulate that result it creates a mismatch and React won't be able to hydrate the page successfully.
  • One reason: becauase I put process.env.ENV_MODE inside SinglePostTemplate ← remove it and everything is good!
  • Read more: Easily Fix React Hydration Errors | Travis Wimer
    • 1// Add below in the client component who has the error
      2const [hydrated, setHydrated] = useState(false)
      3// Make sure all other useHooks are put here
      4
      5useEffect(() => {
      6  setHydrated(true)
      7}, [])
      8
      9if (!hydrated) {
      10  return null
      11}
Cannot find module 'sharp’
Install sharp bên notion-next-js + project chính.
(with SST when deploying to AWS)
1Error: require() of ES Module .../node_modules/string-width/index.js from .../node_modules/@aws-cdk/cloudformation-diff/lib/format-table.js not supported.
2Instead change the require of index.js in .../node_modules/@aws-cdk/cloudformation-diff/lib/format-table.js to a dynamic import() which is available in all CommonJS modules.
→ Thêm "type": "module" in package.jsonyarn reinstall → có thể gặp lỗi với postcss.config.js ← chỉ cần đổi tên thành .cjs là ok! Có thể cũng cần đổi luôn .eslintrc.js nữa!
Warning: Text content did not match. Server:
This SO. ← Using next/dynamic with { ssr: false }
Why dev mode keep reloading?
  • Thay đổi browser thì hết bị (Brave bị, Cốc Cốc không bị)
  • Thay đổi port cũng không bị
Cannot be used as a JSX component.
Sử dụng cái này {/* @ts-expect-error Server Component */} ← tuy nhiên khi build trên vercel sẽ bị lỗi! ← để ko lỗi trên server, dùng {/* @ts-expect-error Client Component */}
Có khi cài lại cái lib bị lỗi thì hết bị, có khi restart vscode???
React refers to UMD global, but the current file is a module
Check this post.
Error: Attempted to call the default export of [project]/src/tools/UuidGeneratorDecoder.tsx from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.
Có element nào đó ở server import element ở client. Hoặc là xoá element client đi, hoặc là làm cho element ở server thành client bằng cách dùng 'use client'.
async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server
As in the error’s description.
Super expression must either be null or a function nextjs 13
You use some “client only” things in a server component. A solution is to move all these things into a child which has “use client” and then integrate that child into the server component which araise the error.
Event handlers cannot be passed to Client Component props onClick={function}
You have to use click handler inside a client component. Put "use client" on the top of that file!
missing field source at line 1 column 2 nextjs
You are importing .scss file in the layout and you forgot to install sass package!
FirebaseAppError: Failed to parse private key: Error: Invalid PEM formatted message. ← \n chatacter in the env variable
Copy private key qua 1 tab mới → chọn find and replace với tuỳ chọn “reg” in vscode → replace \\n by \n → Sau đó copy key và dán vào vercel.
The resource <URL> was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally.
Có 1 cách fix là thay vì import kiểu @root/fontello/fontello.css thì import dạng relative path ../fontello/fontello.css.
Stuck on Creating an optimized production build forever when development server is running
Shutdown dev mode (and other nodejs processes) and run build again.
Loading comments...