An example of a meetups website built with NEXT.js.
Its purpose is to demonstrate SSG/SSR, file-based routing, and backend API routes.
View Demo
·
Report Bug
·
Request Feature
Table of Contents
這個專案用來記錄 NEXT.js 基本的特色與架構寫法,例如以文件目錄系統作為路由管理 (file-based routing)、SSG (static site generation) 和 SSR (server-side rendering) 的實作,以及利用 API route 處理後端相關請求。 Built With
|
我們可以用 _app.js 進行全局設定。除了可以在 _app.js 放入定義好的 globals.css
外,因為裡面的 <Component />
代表每一個頁面,所以將 <Layout>
包住 <Component />
可以將 <Layout>
的設定作用在每一個頁面上。
將檔案放在 pages
資料夾底下就可以在對應的 URL 看到該檔案的頁面。
/pages/index.js => localhost/
/pages/welcome.js => localhost/welcome
在建立 pages
底下建立另外的資料夾,就可以建立巢狀 URL。
/pages/meetup/index.js => localhost/meetup/
/pages/meetup/other.js => localhost/meetup/other
將檔案名用中括號 []
包覆,中間填入的名稱 (e.g.meetupId
) 會作為網址參數 (url params) 被使用。
/pages/[meetupId]/index.js => localhost/123
=> localhost/234
=> ...
# is equal to
# /pages/[meetupId].js
有兩種方式可以取得 URL 上的參數,一個是透過在 component 中使用 useRouter
;另一個是透過在 SSG/SSR 中使用 context.params
取得。
- useRouter
// localhost/123
const router = useRouter();
console.log(router.query.meetupId); // 123
- Context.params (e.g. MeetupDetailPage)
// localhost/123
export const getStaticProps = async (ctx) => {
const meetupId = ctx.params.meetupId; // 123
}
SSG 會在 build time 就透過 API 取得資料,並建立好靜態頁面。伺服器在之後收到 request 時會重複使用這些已經生成好的靜態頁面。若你認為頁面可以在瀏覽器發送請求前就先產生好,並且不會常常改變,推薦使用 SSG。
- getStaticProps 會在伺服器端執行,可以抓取 API 資料,並回傳 props 給 component。另外擁有 context 參數可以獲得 req, res 資訊。
- getStaticPaths 用來定義動態路由可能會產生的路徑 (URLs),解決動態路由可能有無限種可能的路徑。
- fallback 解決用戶遇到無定義在 getStaticPaths 的路由時
false
會直接顯示 404 Not Foundtrue
會馬上顯示空白頁面,並試著去載入正確頁面"blocking"
會卡在原本頁面,等到載入成功才顯示正確頁面
- fallback 解決用戶遇到無定義在 getStaticPaths 的路由時
SSR 指的是伺服器在每次收到請求時,就會重新產生對應的靜態頁面。除非你的頁面的資料會有頻繁的更新,且內容會根據每次的請求而有不同時,在這種情況下才選擇使用 SSR。
- getServerSideProps 做法和 SSG 相同,只是會在收到每次的 request 後都重新渲染。
NEXT.js 提供編寫後端程式碼的功能,只要在 /pages/api/
底下建立後端 API 功能,就可以在任何前端的 component 呼叫該 API。API 一樣會根據 /pages/api/
的架構建立 URL 連結。
/pages/api/new-meetup.js => localhost/api/new-meetup
NEXT.js 可以在 next.config.js
或 vercel
定義環境變數:
const nextConfig = {
...
env: {
MONGODB_ACCOUNT: "XXXXX",
MONGODB_PWD: "XXXXXXXX",
MONGODB_COLLECTION: "XXXXX",
},
};
module.exports = nextConfig;
並且通過 process.env.MONGODB_ACCOUNT
取得該變數。
Distributed under the MIT License. See LICENSE for more information.
Reach out to the maintainer at one of the following places:
- GitHub discussions
- The email which is located in GitHub profile