All posts

How to Fix CORS Policy Blocked Error in Deno

Learn how to fix the CORS Policy Blocked Error in Deno. Step-by-step guide with code examples.

The CORS Policy Blocked Error in Deno can stop your project dead in its tracks. Let's break down what causes it and how to resolve it quickly.

Understanding the Problem

This error occurs when a browser blocks a cross-origin request because the server doesn't include the proper Access-Control-Allow-Origin headers. It's a security mechanism that prevents unauthorized domains from accessing your API.

Solution

The key is to set CORS headers manually in Oak middleware and handle preflight OPTIONS requests:

import { Application } from "https://deno.land/x/oak/mod.ts";

const app = new Application();
app.use(async (ctx, next) => {
  ctx.response.headers.set("Access-Control-Allow-Origin", "https://yourdomain.com");
  ctx.response.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  ctx.response.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
  if (ctx.request.method === "OPTIONS") {
    ctx.response.status = 204;
    return;
  }
  await next();
});

Common Pitfall

Many developers waste time on this by looking in the wrong place. The error message can be misleading — focus on the Deno configuration rather than the application logic itself. This is also a good opportunity to review your Deno project's error handling strategy and make sure similar issues are caught early.

Confirming It Works

To confirm the fix is working, check your Deno application logs for any remaining error traces. You should see clean request/response cycles without the previous error. Deploy to a staging environment to verify the fix holds under production-like conditions.

Going Forward

Tools like [Bugsly](https://bugsly.dev) can catch these Deno errors in real time, giving you stack traces and context to fix issues faster.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free