Next.js App Router 的 route.js(TypeScript 專案寫成 route.ts)用來寫 Route Handlers:在檔案裡匯出跟 HTTP 方法同名的函式,用 Web 標準的 Request 與 Response 處理請求,常用來做 JSON API、接收 Webhook 或輸出 RSS。Route Handlers 從 Next.js 13.2.0 開始提供,只能放在 app 目錄,作用等同 pages 目錄的 API Routes。本文以 Next.js 16(範例在 16.4.3、開啟 cacheComponents 的專案執行)說明寫法、支援的 HTTP 方法、context.params、RouteContext 型別,以及 GET 的快取行為。
最基本的 route.ts
資料夾路徑就是網址路徑,route.ts 放在哪一層就處理哪個網址。下面這個檔案處理 /api/hello:
// app/api/hello/route.ts
export async function GET() {
return Response.json({ message: 'Hello World' })
}
$ curl http://localhost:3000/api/hello
{"message":"Hello World"}
route.ts 匯出的是以 HTTP 方法命名的函式(GET、POST…),回傳值是 Response 物件;用 Response.json() 回傳時,回應標頭是 content-type: application/json。
支援的 HTTP 方法、405 與 OPTIONS
route.ts 支援 GET、POST、PUT、PATCH、DELETE、HEAD、OPTIONS 七種方法,每種方法各匯出一個函式。各方法的用途可以參考 HTTP 請求方法基礎概念。下面在同一個檔案寫列表查詢與新增:
// app/api/items/route.ts
type Item = { id: string; name: string }
// 示範用的記憶體資料,正式專案換成資料庫
const items: Item[] = [
{ id: '1', name: '機械鍵盤' },
{ id: '2', name: '27 吋螢幕' },
]
export async function GET() {
return Response.json(items)
}
export async function POST(request: Request) {
const body = await request.json()
if (typeof body.name !== 'string' || body.name.trim() === '') {
return Response.json({ error: 'name 必填' }, { status: 400 })
}
const item = { id: String(items.length + 1), name: body.name }
items.push(item)
return Response.json(item, { status: 201 })
}
Response.json() 的第二個參數可以指定狀態碼與標頭。送出請求的結果:
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"USB-C Hub"}' http://localhost:3000/api/items
HTTP/1.1 201 Created
{"id":"3","name":"USB-C Hub"}
$ curl -X POST -H "Content-Type: application/json" -d '{}' http://localhost:3000/api/items
HTTP/1.1 400 Bad Request
{"error":"name 必填"}
讀取請求主體用 Web 標準方法:JSON 用 request.json(),表單用 request.formData(),純文字(例如要自己驗簽的 Webhook)用 request.text()。不需要像 Pages Router 的 API Routes 設定 bodyParser。
檔案沒有匯出的方法會由 Next.js 處理:
- 呼叫檔案裡沒有定義的方法,回
405 Method Not Allowed。 - 沒有定義
OPTIONS時,Next.js 自動實作,並依檔案裡有的方法設定Allow標頭。
$ curl -X PUT -i http://localhost:3000/api/items/1
HTTP/1.1 405 Method Not Allowed
$ curl -X OPTIONS -i http://localhost:3000/api/items/1
HTTP/1.1 204 No Content
allow: DELETE, GET, HEAD, OPTIONS
動態路由:context.params 是 Promise
route.ts 也能放在動態區段資料夾裡(例如 [id])。函式的第二個參數 context 裡的 params 是 Promise,要先 await 才拿得到值,這是 Next.js 15.0.0-RC 起的寫法。TypeScript 專案可以用全域的 RouteContext 型別,傳入路由字串就會得到對應的 params 型別,不用 import:
// app/api/items/[id]/route.ts
import type { NextRequest } from 'next/server'
const items: Record<string, string> = { '1': '機械鍵盤', '2': '27 吋螢幕' }
export async function GET(
_request: NextRequest,
ctx: RouteContext<'/api/items/[id]'>
) {
const { id } = await ctx.params
const name = items[id]
if (!name) {
return Response.json({ error: '找不到商品' }, { status: 404 })
}
return Response.json({ id, name })
}
export async function DELETE(
_request: NextRequest,
ctx: RouteContext<'/api/items/[id]'>
) {
const { id } = await ctx.params
delete items[id]
return new Response(null, { status: 204 })
}
$ curl http://localhost:3000/api/items/1
{"id":"1","name":"機械鍵盤"}
$ curl -i http://localhost:3000/api/items/9
HTTP/1.1 404 Not Found
{"error":"找不到商品"}
RouteContext 的型別在執行 next dev、next build 或 next typegen 時產生,剛新增的路由要先跑過其中一個指令,編輯器才認得。不用 RouteContext 時,也可以直接寫 { params }: { params: Promise<{ id: string }> }。[...slug] 這類 catch-all 區段的 params 值是字串陣列,區段寫法可以參考 Next.js 動態路由 Dynamic Segments 用法。
讀取查詢參數、標頭與 cookie
第一個參數 request 實際上是 NextRequest,它延伸了 Web 的 Request,多了解析好的 nextUrl 與 cookies:
// app/api/search/route.ts
import type { NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const query = request.nextUrl.searchParams.get('query')
return Response.json({ query })
}
/api/search?query=hello 回傳 {"query":"hello"}。標頭與 cookie 也可以用 next/headers 的 headers()、cookies() 讀取,兩者都要 await:
// app/api/user-agent/route.ts
import { headers } from 'next/headers'
export async function GET() {
const headersList = await headers()
const userAgent = headersList.get('user-agent')
return Response.json({ userAgent })
}
headers() 回傳的是唯讀物件,要加回應標頭時,在 new Response() 或 Response.json() 的第二個參數設定 headers。
GET 會不會被快取:看有沒有開 cacheComponents
開啟 cacheComponents(Next.js 16)
next.config.ts 設了 cacheComponents: true 時,GET 的 Route Handler 和一般頁面同一套規則:預設在請求時執行;沒有讀取未快取資料或執行期資料時,next build 會預先產生。以本文的範例執行 next build,路由表如下(○ 是預先產生的靜態內容,ƒ 是每次請求執行):
├ ○ /api/hello
├ ƒ /api/items
├ ƒ /api/items/[id]
├ ƒ /api/random
├ ƒ /api/search
├ ƒ /api/user-agent
/api/hello 只回傳固定內容,所以是 ○,next start 後回應帶 x-nextjs-cache: HIT。/api/random 呼叫了 Math.random(),/api/user-agent 呼叫了 headers(),/api/search 讀了 request.nextUrl,都是 ƒ。官方文件列出的中止條件包括:網路請求、資料庫查詢、非同步檔案操作、讀取 request 的屬性(req.url、request.headers、request.cookies、request.body)、cookies()、headers()、connection(),以及非確定性的操作。
/api/items 的 GET 只回傳模組裡的陣列,但同一個檔案還匯出 POST,next build 一樣標成 ƒ,沒有預先產生。需要 GET 預先產生時,不要把它和其他方法放在同一個檔案。
想快取資料庫或外部 API 的結果,把讀資料的部分抽成函式,加上 'use cache' 與 cacheLife()。'use cache' 不能直接寫在 GET 函式本體裡:
// app/api/products/route.ts
import { cacheLife } from 'next/cache'
export async function GET() {
const products = await getProducts()
return Response.json(products)
}
async function getProducts() {
'use cache'
cacheLife('hours')
// 示範用:正式專案換成資料庫查詢
return {
items: [
{ id: 1, name: '機械鍵盤' },
{ id: 2, name: '27 吋螢幕' },
],
generatedAt: new Date().toISOString(),
}
}
next build 把這條路由標成 ○,Revalidate 欄是 1h、Expire 欄是 1d;連續請求拿到相同的 generatedAt,回應標頭是 cache-control: s-maxage=3600, stale-while-revalidate=82800。cacheLife 的其他設定可以參考 Next.js use cache 指令用法。
舊教學常見的 export const dynamic = 'force-static',在開啟 cacheComponents 的專案會讓 next build 失敗:
Error: Route segment config "dynamic" is not compatible with `nextConfig.cacheComponents`. Please remove it.
Next.js 16.0.0 起,開啟 cacheComponents 時移除了 dynamic、dynamicParams、revalidate、fetchCache 這幾個區段設定。官方的遷移方式就是上面的寫法:拿掉 dynamic,改成呼叫加了 'use cache' 的函式。
沒有開 cacheComponents
沒有開 cacheComponents 時,Route Handlers 預設不快取。只有 GET 可以選擇快取,做法是在檔案加 export const dynamic = 'force-static' 這類區段設定;POST 等其他方法就算和快取的 GET 放在同一個檔案,也不會被快取。Next.js 15.0.0-RC 以前 GET 預設是靜態快取,從 14 升級的專案要留意這個差異。
回傳 JSON 以外的內容
route.ts 不限回傳 JSON,資料夾名稱可以帶副檔名,例如用 app/rss.xml/route.ts 輸出 RSS:
// app/rss.xml/route.ts
export async function GET() {
return new Response(
`<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>Sean 的技術筆記</title>
<link>https://seanacnet.com/</link>
<description>前端與後端開發筆記</description>
</channel>
</rss>`,
{ headers: { 'Content-Type': 'text/xml' } }
)
}
/rss.xml 回應 content-type: text/xml。sitemap.xml、robots.txt、網站圖示與 Open Graph 圖片,Next.js 另有專用的 metadata 檔案慣例,不必自己寫 Route Handler。
注意事項
route.js 不能和 page.js 放在同一層
每個 route.js 或 page.js 都會接管該路由的所有 HTTP 方法,所以同一層只能有其中一個:app/page.tsx 和 app/route.ts 衝突,app/page.tsx 和 app/api/route.ts 就沒問題。兩個放在同一層時,next build 會失敗:
Conflicting route and page at /dashboard: route at /dashboard/route and page at /dashboard/page
頁面元件的寫法可以參考 Next.js page.js 用法。
route 不參與 layout 與用戶端導覽
官方文件把 route 稱為最底層的路由元件:它不參與 layout,也不參與 page 那樣的用戶端導覽,回應就是函式回傳的 Response,不會被 layout.js 包住。
多個 Route Handler 共用 CORS 標頭
單一 Route Handler 可以在回應加上 Access-Control-Allow-Origin 等標頭;很多支 API 都要時,可以改在 Proxy 或 next.config.js 的 headers 統一設定,Proxy 寫法見 Next.js proxy.js 用法。
參考資料與延伸閱讀
- Next.js Docs: route.js
- Next.js Docs: Route Handlers
- Next.js Docs: Route Segment Config
- Next.js Docs: Migrating to Cache Components
- 淺談 HTTP 請求方法 (HTTP Request Methods):GET、POST、PUT、DELETE 基礎概念與 Fetch 入門
- Next.js 動態路由 Dynamic Segments 用法:[slug]、[…slug]、[[…slug]] 與 generateStaticParams
- Next.js use cache 指令用法:函式、元件與檔案層級快取、cacheLife 與 cacheTag
- Next.js page.js 用法:params、searchParams、PageProps 型別與 Client Component 頁面
- Next.js proxy.js 用法:取代 middleware 的 proxy 函式、matcher 設定與 Node.js runtime
發佈留言