在開發 React 專案時,如何讓同一個 function 同時適用於 client side 與 server side(RSC)?本文示範如何透過 react-server 條件 export 與 server-only,實現乾淨又安全的雙端共用邏輯設定,並提供可直接使用的範例程式碼。
Written by: Chia1104 CC BY-NC-SA 4.0
之前在開發個人專案時,遇到一個狀況那就是同一個 function 我想要在 react 的 client side 跟 server side (RSC) 都能被引用,但裡面會做微調,例如我在 server side 的請求會在多帶一組 client secret 的 headers
import "server-only";
import { createAuthClient } from "better-auth/client";
import { X_INTERNAL_REQUEST_SECRET } from "@chia/utils";
import { env } from "./env";
import { baseAuthClient } from "./utils";
export const authClient = createAuthClient(
baseAuthClient({
fetchOptions: {
headers: {
[X_INTERNAL_REQUEST_SECRET]: env.INTERNAL_REQUEST_SECRET ?? "",
},
},
})
);而 react 提供了一種基於 es module 暴露檔案的方式,那就是透過 react-server 做 export。
這裡要注意 default 的 export 要寫在最下面,以免被覆蓋。
{
"$schema": "https://json.schemastore.org/package",
"name": "@chia/auth",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
"./client": {
"types": "./src/client.ts",
"react-server": "./src/client.rsc.ts",
"default": "./src/client.ts"
}
}
}並且可以在該檔案中 import "server-only" 來確保該方法不會在 client side 被載入。
該方法可以參考 react rfcs 0277