次のような場合に使用: HTTP値(ウェブエンドポイント、API ルート、ウェブフック(外部サービスからのデータ受信)の受け取り役、または HTTP リクエストに応答するあらゆる値)を構築する際。 ハンドラーのシグネチャ(関数の形式)、Hono(ウェブアプリ構築ツール)の使い方、エンドポイントの URL、CORS(異なるドメイン間でのデータ取得許可)の動作、リダイレクト、および Val Town 独自の制限事項をカバーしています。
Use when building an HTTP val — a web endpoint, API route, webhook receiver, or any val that responds to HTTP requests. Covers the handler signature, Hono usage, the endpoint URL, CORS behavior, redirects, and Val Town-specific limitations.
HTTPバル(fileType: "http")はリクエストハンドラーをエクスポートし、すべての受信HTTPリクエストで実行されます。各HTTPファイルにはライブURLが割り当てられます。URLを自分で作成してはいけません。list_filesまたはcreate_fileのレスポンスからlinks.endpointを読むか、fetch_val_endpointを呼び出してください。
そのURLは誰でもアクセスできます。ただし、バルのアプリアクセス設定(httpPrivacy)がrestricted(制限付き)の場合、認証されていない呼び出し元は、あなたのレスポンスの代わりに302リダイレクトでログインページに送られます。詳細はrestricted-accessスキルを参照してください。
// 詳細: https://docs.val.town/vals/http/
export default async function (req: Request): Promise<Response> {
return Response.json({ ok: true });
}
ファイルにはexportが必要です。ハンドラーはexport defaultで指定します。
Honoを使う場合は、appではなくapp.fetchをエクスポートしてください:
import { Hono } from "npm:hono";
import { parseVal, serveImmutableFile } from "https://esm.town/v/std/utils/index.ts";
const app = new Hono();
app.get("/", (c) => c.text("hello"));
// 不変アセットのキャッシング(client-side-jsスキル参照):
// HTMLシェルがimmutableFileUrl()で付与するURL形式を配信
app.get("/__immutable/*", (c) => serveImmutableFile(c.req.path));
// ソースコード表示へのリダイレクト
app.get("/source", (c) => c.redirect(parseVal().links.self.val));
// エラー時に完全なスタックトレースを得るため必ず追加してください:
app.onError((err) => Promise.reject(err));
export default app.fetch;
HonoのserveStaticはVal Townで動作しません。静的ファイルにはstd/utilsのserveFileまたはstaticHTTPServerを使ってください。完全なstd/utils API(readFile、serveFile、staticHTTPServer、listFiles、listFilesByPath、httpEndpoint、parseValなど)については、https://utilities.val.run/docs.mdを参照してください。
Val Townはデフォルトで緩いCORSヘッダーを追加します(Access-Control-Allow-Origin: *)。ほとんどの場合、CORSについて何もする必要はありません。Honoのcorsミドルウェア(機能拡張)を使うのはほぼ不要です。
重要な注意: CORSヘッダーを自分で設定した場合、Val Townのデフォルトヘッダーはすべて追加されなくなります。CORSを完全に自分で処理するか、全く触らないかのどちらかにしてください。
Response.redirectはVal Townで正しく動作しません。代わりに以下のいずれかを使用してください:
return new Response(null, { status: 302, headers: { Location: "/path" } });
// または、Honoの場合:
return c.redirect("/path");
WebSocket: Val Townは受信するWebSocket接続を受け付けません。ポーリング(定期的なアクセス)、ロングポーリング(接続待機)、またはサーバー送信イベント(サーバーからの通知)を使用してください。
ファイルシステムアクセス: プラットフォームの制約を参照してください。状態を永続的に保存する必要がある場合は、std/sqliteまたはstd/blobを使用してください。
HTML レスポンスの場合、このスクリプトタグを追加して、ブラウザーのエラーをバルのログに送信してください(get_logsで確認できます):
<script src="https://esm.town/v/std/catch"></script>
HTTPバルを編集した後、それを取得してみて、期待されたHTTPレスポンスが返されることを確認してください。この確認なしに変更完了と報告しないでください。
HTTP vals (fileType: "http") export a request handler and run on every incoming HTTP request. Each HTTP file is assigned a live URL — never construct it yourself; read links.endpoint from list_files or create_file responses, or call fetch_val_endpoint.
That URL is open to anyone unless the val's app access (httpPrivacy) is restricted, in which case unauthenticated callers get a 302 to a login page instead of your response — see the restricted-access skill.
// Learn more: https://docs.val.town/vals/http/
export default async function (req: Request): Promise<Response> {
return Response.json({ ok: true });
}
The file must have an export — export default for the handler.
When using Hono, export app.fetch (not app):
import { Hono } from "npm:hono";
import { parseVal, serveImmutableFile } from "https://esm.town/v/std/utils/index.ts";
const app = new Hono();
app.get("/", (c) => c.text("hello"));
// Immutable asset caching (see the client-side-js skill): serves the
// current-version URLs your HTML shell stamps with immutableFileUrl()
app.get("/__immutable/*", (c) => serveImmutableFile(c.req.path));
// View source redirect
app.get("/source", (c) => c.redirect(parseVal().links.self.val));
// Always add this for full stack traces on errors:
app.onError((err) => Promise.reject(err));
export default app.fetch;
Hono's serveStatic does not work on Val Town. Use serveFile / staticHTTPServer from std/utils for static files. For the full std/utils API (readFile, serveFile, staticHTTPServer, listFiles, listFilesByPath, httpEndpoint, parseVal, …), fetch https://utilities.val.run/docs.md.
Val Town adds permissive CORS headers by default (Access-Control-Allow-Origin: *), so in 99% of cases, you should never need to do anything with CORS. Using Hono's cors middleware is almost always unnecessary.
If you set any CORS header yourself, Val Town stops adding all default headers — so either handle CORS completely yourself or don't touch it at all.
Response.redirect is broken on Val Town. Use one of:
return new Response(null, { status: 302, headers: { Location: "/path" } });
// or, with Hono:
return c.redirect("/path");
std/sqlite or std/blob.For HTML responses, add this script tag to send browser errors back to val logs (visible via get_logs):
<script src="https://esm.town/v/std/catch"></script>
After editing an HTTP val, fetch it to confirm it returns the expected HTTP response. Do not report a change as done without this step.
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。