Heidi-Liu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    [![hackmd-github-sync-badge](https://hackmd.io/fufpeNLzSu-Wgut0fBOg2w/badge)](https://hackmd.io/fufpeNLzSu-Wgut0fBOg2w) ###### `Front-End` `React` `Next.js` # 【學習筆記】Next.js 錯誤修復紀錄: 「Window is not defined」、「use client & missing generateStaticParams() error」 [toc] ## 前言 這篇主要用來記錄 Next.js 開發過程採的坑,後續也會不定期更新: + 問題一:如何修復 `"Window is not defined"` error + 問題二:在 use client 頁面實作動態路由顯示 `missing generateStaticParams()` error ## 問題一:如何修復 "Window is not defined" error in Next.js 事情發生在開發 Next.js APP,要實作 Google 登入驗證,需要使用 [Window](https://developer.mozilla.org/en-US/docs/Web/API/Window)、[Document](https://developer.mozilla.org/en-US/docs/Web/API/Document) 物件時,發現程式會報出以下錯誤: ```= ReferenceError: window is not defined or ReferenceError: document is not defined ``` ### 發生原因 這是由於 Next.js 預設為伺服器渲染(Server-side Rendering),會在 Node.js 環境下預渲染頁面,並將生成的 HTML 內容發送給 Client 端。 因此渲染過程是在 Server 端而非在瀏覽器中,由於程式無法識別 Window / Document 物件而回報上述 Error。 ### 如何解決? 解決方法可透過條件渲染(Conditional Rendering),確保 Next.js 只在 Client 端執行指定的程式碼, 可透過以下兩種方式來實現: + 檢查 window 是否存在 + 使用 useEffect hook #### (1) 檢查 window 是否存在 判斷 window 是否存在,確定在瀏覽器中才執行指定的程式碼: ```typescript= const isBrowser = () => typeof window !== 'undefined'; if (typeof window !== 'undefined') { // Client-side-only console.log('window: ', window); }; ``` #### (2) 使用 useEffect 等 Hooks 透過 useEffect 等方法,可確保程式碼只會在 Client 端執行: ```typescript= 'use client'; import React, { useEffect } from 'react'; // ... useEffect(() => { // Client-side-only console.log('window: ', window); window.addEventListener('scroll', (e) => { console.log('srcoll: ', e) }) },[]) ``` ### 參考資料 + [Window is not defined in Next.js React app](https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app) + [如何修复Next.js中的 "window is not defined"? - 掘金](https://juejin.cn/s/react%20window%20is%20not%20defined%20next%20js) ## 問題二:在 use client 頁面實作動態路由顯示 `missing generateStaticParams()` error 事情發生在開發 Next.js APP,實作 dynamic routing 時(如:`server/[evo]/page.tsx`),會顯示以下錯誤: ![error](https://hackmd.io/_uploads/HJ8MieYbA.png) 上述錯誤訊息中的`"output: export"`,是 Next.js 提供支援 [Static Exports(靜態導出)](https://nextjs.org/docs/app/building-your-application/deploying/static-exports),透過在設定檔 `next.config.js` 加上參數: ```javascript= /** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // Outputs a Single-Page Application (SPA) export default nextConfig ``` 如此一來,即可在 `next build` 建置時實現 SPA (single-page application),將會在 `out` 資料夾底下生成靜態檔案,將每個路由分解為單獨的 HTML 檔案,避免在 Client 端載入不必要的 JS 程式碼,減少 bundle 大小以提高頁面效能。 ### 發生原因 但在 Next.js 若想要實現 Dynamic Routes(動態路由),必須加上 `generateStaticParams()` 方法,這段 function 只能在 Server Component 執行,在 Client Component 並不支援。 [官方文件(Deploying: Static Exports | Next.js)](https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features) 也提到 App Routing 若想要 Dynamic Routes 必須搭配「只能在 SSR 運行的 `generateStaticParams()`」: ![unsupported](https://hackmd.io/_uploads/S1xrigt-A.png) ### 如何解決? 如果想要輸出 SPA,又希望能在 `'use client'` 情境中實現動態路由,則需要將元件拆成兩個部分實作: + 在 Server Component 引入 `generateStaticParams()` 方法,以實現動態路由 + 接著引入 Client Component,即可使用 Hooks 以下是範例程式碼,詳細可參考這篇文章[《usage of generateStaticParams with use client | by Vivi - Medium》](https://medium.com/@givvemeee/usage-of-generatestaticparams-with-use-client-a059c23f7316) + `server/[evo]/page.tsx`:在 Server Component 引入 `generateStaticParams()` 方法,以實現動態路由 ```typescript= // server/[evo]/page.tsx import EvoPage, { Props } from "."; export function generateStaticParams() { return [ { evo: 'test' }, { evo: 'stage' }, { evo: 'public' } ]; } export default function ServerEvoPage({ params }: Props) { console.log('[ServerEvoPage] params', params) return <EvoPage params={{ evo: params.evo }}/>; } ``` + `server/[evo]/index.tsx`:在上述 Server Component 引入 Client Component,即可使用 Hooks: ```typescript= // server/[evo]/index.tsx 'use client'; import React from 'react'; export type Props = { params: { evo: string}; }; export default function EvoPage({ params }: Props) { console.log('[EvoPage] params: ', params); const [data, setData] = React.useState(''); return ( <div> This is Client Component. </div> ); } ``` ### 參考資料 + [[NEXT-1049] use client with generateStaticParams will opt out of static generation #46735](https://github.com/vercel/next.js/issues/46735) + [[NEXT-1030] output: 'export' with use client in dynamic routes doesn't work #48022](https://github.com/vercel/next.js/issues/48022) + [App Router with output: export does not support useParams() on client #54393](https://github.com/vercel/next.js/issues/54393) + [NextJs-静态导出](https://www.yuansudong.net/document/NextJs/35.%E9%9D%99%E6%80%81%E5%AF%BC%E5%87%BA.html) + [Day 19 - Next.js 13 App Router 動態路由 Dynamic Routes & getStaticParams()](https://ithelp.ithome.com.tw/articles/10322261)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully