次のような場合に使用: 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のval(fileType: "http")はリクエストハンドラーをエクスポートし、受け取ったすべてのHTTPリクエストに対して動作します。各HTTPファイルには専用のURLが自動で割り当てられます。URLを自分で作成してはいけません。list_filesやcreate_fileレスポンスのlinks.endpointから読み込むか、fetch_val_endpointを呼び出してURLを取得してください。
そのURLは誰でもアクセスできます。ただし、valのアプリアクセス設定(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: *)を自動で追加するため、ほぼ全てのケースで何もする必要はありません。Honoのcorsミドルウェア(処理の中間層)を使うことはほぼ不要です。
自分でCORSヘッダーを1つでも設定すると、Val Townのデフォルトヘッダーはすべて追加されなくなります。そのため、CORS処理を完全に自分で実装するか、触らないかのどちらかにしてください。
Val TownではResponse.redirectが正常に動作しません。以下のいずれかを使ってください:
return new Response(null, { status: 302, headers: { Location: "/path" } });
// または Hono の場合:
return c.redirect("/path");
std/sqliteまたはstd/blobを使用してください。HTML応答の場合、このスクリプトタグを追加することで、ブラウザで発生したエラーをvalのログに送信できます(get_logsで確認可能):
<script src="https://esm.town/v/std/catch"></script>
HTTPのvalを編集した後、実際に取得して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 による自動翻訳です。