How to enable API requests in Fresh
Published on , 437 words, 2 minutes to read

We can't trust browsers because they are designed to execute arbitrary code from website publishers. One of the biggest protections we have is Cross-Origin Request Sharing (CORS), which prevents JavaScript from making HTTP requests to different domains than the one the page is running under.
Fresh is a web framework for
Deno that enables rapid development and is the
thing that I am rapidly reaching to when developing web applications.
One of the big pain points is making HTTP requests to a different
origin (such as making an HTTP request to api.example.com when your
application is on example.com). The Fresh documentation doesn't have
any examples of enabling CORS.
In order to customize the CORS settings for a Fresh app, copy the
following middleware into routes/_middleware.ts:
// routes/_middleware.ts
import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler(
req: Request,
ctx: MiddlewareHandlerContext<State>
) {
const resp = await ctx.next();
resp.headers.set("Access-Control-Allow-Origin", "*");
return resp;
}
If you need to customize the CORS settings, here's the HTTP headers you should take a look at:
| Header | Use | Example |
|---|---|---|
Access-Control-Allow-Origin | Allows arbitrary origins for requests, such as * for all origins. | https://xeiaso.net, https://api.xeiaso.net |
Access-Control-Allow-Methods | Allows arbitrary HTTP methods for requests, such as * for all methods. | PUT, GET, DELETE |
Access-Control-Allow-Headers | Allows arbitrary HTTP headers for requests, such as * for all headers. | X-Api-Key, Xesite-Trace-Id |
This should fix your issues.
Facts and circumstances may have changed since publication. Please contact me before jumping to conclusions if something seems wrong or unclear.
Tags: fresh, deno, preact