encore-frontend について
encore-frontendは、EncoreのAPI定義から型付きTypeScriptクライアントを生成し、React、TanStack Query、Next.jsで利用する方法を案内します。CORSや認証リクエストの設定も扱います。
主な機能
- 01型付きTypeScriptクライアントの生成
- 02Reactでの利用例
- 03TanStack Queryの利用例
- 04Next.jsサーバーコンポーネントの例
- 05CORSと認証の設定案内
活用シーン
- 01ローカル環境やデプロイ環境向けのクライアント生成
- 02Reactページでのバックエンドデータ取得
- 03Next.jsサーバーコンポーネントからのAPI呼び出し
- 04CORSと認証リクエストの設定
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ encoredev/ skills --skill encore-frontendインストール後、Claude Code で/encore-frontendを入力して読み込まれたか確認します。
詳細
Encore によるフロントエンド統合
手順
Encore は、フロントエンドアプリケーションをバックエンド API に接続するためのツールを提供します。
TypeScript クライアントの生成
# Generate client for local development
encore gen client --output=./frontend/src/client.ts --env=local
# Generate client for a deployed environment
encore gen client --output=./frontend/src/client.ts --env=staging
これにより、API 定義に基づいて完全に型付けされたクライアントが生成されます。
生成されたクライアントの使用
// frontend/src/client.ts is auto-generated
import Client from "./client";
const client = new Client("http://localhost:4000");
// Fully typed API calls
const user = await client.user.getUser({ id: "123" });
console.log(user.email);
const newUser = await client.user.createUser({
email: "[email protected]",
name: "New User",
});
React の例
// frontend/src/components/UserProfile.tsx
import { useState, useEffect } from "react";
import Client from "../client";
const client = new Client(import.meta.env.VITE_API_URL);
export function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
client.user.getUser({ id: userId })
.then(setUser)
.catch(setError)
.finally(() => setLoading(false));
}, [userId]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
TanStack Query を使った React
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import Client from "../client";
const client = new Client(import.meta.env.VITE_API_URL);
export function UserProfile({ userId }: { userId: string }) {
const { data: user, isLoading, error } = useQuery({
queryKey: ["user", userId],
queryFn: () => client.user.getUser({ id: userId }),
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{user.name}</div>;
}
export function CreateUserForm() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: (data: { email: string; name: string }) =>
client.user.createUser(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["users"] });
},
});
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
mutation.mutate({
email: formData.get("email") as string,
name: formData.get("name") as string,
});
};
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" required />
<input name="name" required />
<button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? "Creating..." : "Create User"}
</button>
</form>
);
}
Next.js サーバーコンポーネント
// app/users/[id]/page.tsx
import Client from "@/lib/client";
const client = new Client(process.env.API_URL);
export default async function UserPage({ params }: { params: { id: string } }) {
const user = await client.user.getUser({ id: params.id });
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
CORS の設定
encore.app ファイルで CORS を設定します:
{
"id": "my-app",
"global_cors": {
"allow_origins_with_credentials": [
"http://localhost:3000",
"https://myapp.com",
"https://*.myapp.com"
]
}
}
CORS オプション
| オプション | 説明 |
|---|---|
allow_origins_without_credentials | 認証情報を伴わないリクエストで許可されるオリジン(デフォルト: ["*"]) |
allow_origins_with_credentials | 認証情報を伴うリクエスト(Cookie、認証ヘッダー)で許可されるオリジン |
allow_headers | 許可する追加のリクエストヘッダー |
expose_headers | 公開する追加のレスポンスヘッダー |
debug | CORS デバッグログを有効にする |
フロントエンドからの認証
認証済みリクエストでは、Authorization ヘッダーを渡します:
// Using fetch
const response = await fetch("http://localhost:4000/profile", {
headers: {
"Authorization": `Bearer ${token}`,
},
});
// Or include credentials for cookie-based auth
const response = await fetch("http://localhost:4000/profile", {
credentials: "include",
});
TanStack Query では、デフォルトのフェッチャーを設定します:
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: async ({ queryKey }) => {
const response = await fetch(queryKey[0] as string, {
headers: { Authorization: `Bearer ${getToken()}` },
});
if (!response.ok) throw new Error("Request failed");
return response.json();
},
},
},
});
素の Fetch の使用
生成されたクライアントを使いたくない場合:
async function getUser(id: string) {
const response = await fetch(`http://localhost:4000/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
}
async function createUser(email: string, name: string) {
const response = await fetch("http://localhost:4000/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, name }),
});
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
}
環境変数
# .env.local (Next.js)
NEXT_PUBLIC_API_URL=http://localhost:4000
# .env (Vite)
VITE_API_URL=http://localhost:4000
ガイドライン
encore gen clientを使用して型付き API クライアントを生成します- API が変更されたらクライアントを再生成します
- 本番ドメイン用に
encore.appで CORS を設定します - 認証済みリクエストには
allow_origins_with_credentialsを使用します - トークンベースの認証には
Authorizationヘッダーを含めます - Cookie ベースの認証には
credentials: "include"を使用します - API URL には環境変数を使用します(環境ごとに異なります)
- 生成されたクライアントはエラーと型を自動的に処理します
コメント
Markdown 対応