How to ... in Next.js -02

How to ... in Next.js -02

Route Handlers

  • 允許在 Next.js 專案內建立 custom API。

  • File convention 是 route.js

  • 不能與 page.js存在於同一層 route segment ,會造成衝突。

  • Next.js 提供 NextRequestNextResponse 作為原生 RequestResponse API 的擴充。

// app/api/route.js
export async function GET() {
  const res = await fetch('https://data.mongodb-api.com/...', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY,
    },
  })
  const data = await res.json()

  return Response.json({ data })
}

cookies

  • cookies function 可以讓你在 server component 中讀取 HTTP Request 進來的 cookies。

      import { cookies } from 'next/headers'
    
      export default function Page() {
        const cookieStore = cookies()
        const theme = cookieStore.get('theme')
        return '...'
      }
    
  • 由於 cookies function 是 dynamic function,無法事先得知 cookies 值。因此如果有在 layout 或是 page 的地方使用 cookies function,就會是 dynamic rendering。

  • 可以使用 cookies function 有:server component、server action、Route Handler。

error.js

不論是在 server component 還是 client component 有 error 發生時(throw an error),會 render 的 fallback UI。