Code on demand (COD) is an optional REST constraint: a server returns executable code that gives a client additional behavior. A browser, for example, can download JavaScript that renders an interface or makes further HTTP requests. COD can improve performance and scalability, but executing supplied code reduces visibility and brings security risks. section 1.1.4 section 3.1.5
An API that primarily returns JSON may have little reason to use COD. For a concrete exception, a `/cod/test` endpoint can return HTML that checks whether the calling browser runs JavaScript and displays the result. section 3.1.5
The test endpoint has three parts:
- Map a GET request to `/cod/test` and return the response as `text/html`. section 3.1.5
- Include a `<script>` that shows an alert with server and client UTC times when JavaScript runs. section 3.1.5
- Include a `<noscript>` message for a browser with JavaScript disabled; apply the `AnyOrigin` CORS policy and prevent response caching with `NoStore = true`. section 3.1.5
app.MapGet("/cod/test",
[EnableCors("AnyOrigin")]
[ResponseCache(NoStore = true)] () =>
Results.Text("<script>" +
"window.alert('Your client supports JavaScript!" +
"\\r\\n\\r\\n" +
$"Server time (UTC): {DateTime.UtcNow.ToString("o")}" +
"\\r\\n" +
"Client time (UTC): ' + new Date().toISOString());" +
"</script>" +
"<noscript>Your client does not support JavaScript</noscript>",
"text/html"));
The Minimal API listing puts the route, response content, CORS policy, and no-store setting together. section 3.1.5
Open the route with JavaScript enabled to check for the alert, then disable JavaScript and reload it to check for the text fallback. This demonstrates client-executed code without making COD a requirement for every RESTful API. section 1.1.4 section 3.1.5
