Readme

CORS issues are the bane of frontend engineers.

In Val Town, if you don't customize any CORS headers, we add these defaults:

Access-Control-Allow-Origin: "*"
Access-Control-Allow-Methods: "GET,HEAD,PUT,PATCH,POST,DELETE"

You can override them if you wish to disallow CORS. Check out @neverstew/setCorsHeaders for the easiest way to do this in your code.

This val is a client-side-rendered React app that makes requests to @stevekrouse/cors_example_backend. The backend is in a different val because CORS applies to requests on different domains. The backend has examples of the default permissive CORS behavior and disabled CORS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/** @jsxImportSource https://esm.sh/react */
import { useState } from "https://esm.sh/react@18.2.0";
import react_http from "https://esm.town/v/stevekrouse/react_http";
const BASE_URL = "https://stevekrouse-cors_example_backend.web.val.run";
export function App() {
const [logs, setLogs] = useState([]);
async function request(url, options) {
try {
const response = await fetch(url, options);
const status = response.status;
const data = await response.text();
setLogs([...logs, `${options?.method || "GET"} ${url} [${status}] ${data}`]);
} catch (error) {
setLogs([...logs, `${options?.method || "GET"} ${url} ${error}`]);
}
}
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<h1>CORS Example</h1>
<button onClick={() => request(BASE_URL + "/default", { method: "GET" })}>GET /default</button>
<button onClick={() => request(BASE_URL + "/default", { method: "POST" })}>POST /default</button>
<button onClick={() => request(BASE_URL + "/no_cors", { method: "GET" })}>GET /no_cors</button>
<button onClick={() => request(BASE_URL + "/no_cors", { method: "POST" })}>POST /no_cors</button>
<h2>Logs</h2>
<pre>{logs.join("\n")}</pre>
</div>
);
}
export default react_http(App, import.meta.url);
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.