Handling Preflight Requests in Deno
When building web applications, especially those that interact with APIs, you may encounter a concept known as “preflight requests.” These are part of the Cross-Origin Resource Sharing (CORS) protocol, which is crucial for web security. In this blog post, we will explore what preflight requests are and how to handle them in a Deno application using TypeScript.
What Are Preflight Requests?
A preflight request is an HTTP request that browsers send to check if the server is willing to accept a particular cross-origin request. This typically occurs when a client (like a web application) sends a request to a different origin (domain, protocol, or port) than its own.
Preflight requests are made using the OPTIONS
HTTP method. They are sent before the actual request to determine whether the actual request is safe to send. The server responds with the appropriate CORS headers to indicate whether the request is allowed.
When Are Preflight Requests Triggered?
Preflight requests are triggered under the following conditions:
- HTTP Methods: If the request uses methods other than GET, POST, or HEAD.
- Custom Headers: If the request includes headers not considered “simple,” such as custom headers.
- Content Types: If the request’s content type is not one of the following:
application/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
.
Handling Preflight Requests in Deno with TypeScript
Step 1: Implementing the Server
Create server.ts
file, you can set up an HTTP server that handles preflight requests. Here’s a simple example:
import { serve } from "https://deno.land/std/http/server.ts";
const handler = async (request: Request): Promise<Response> => {
// Handle preflight requests
if (request.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*", // Allow any origin
"Access-Control-Allow-Methods": "GET, POST, OPTIONS", // Allowed methods
"Access-Control-Allow-Headers": "Content-Type, Authorization", // Allowed headers
"Access-Control-Max-Age": "86400", // Cache preflight response for 1 day
},
});
}
// Handle actual requests
if (request.method === "POST") {
const body = await request.json();
return new Response(JSON.stringify({ message: "Success", data: body }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
return new Response("Method Not Allowed", { status: 405 });
};
const server = serve({ port: 8000 });
console.log("Server running on http://localhost:8000");
for await (const request of server) {
request.respond(await handler(request));
}
Step 2: Running the Server
To run your Deno server, use the following command in your terminal:
deno run --allow-net server.ts
Step 3: Testing the Server
You can test the server using a tool like Postman or curl. For example, to test the preflight request:
curl -X OPTIONS http://localhost:8000 -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST"
You should receive a response with status 204 and the appropriate CORS headers.
Conclusion
Handling preflight requests is an essential aspect of building secure web applications that interact with APIs across different origins. By following the steps outlined in this post, you can effectively manage preflight requests in your Deno application using TypeScript. This ensures that your application adheres to CORS policies while allowing seamless communication with external resources.
Latest blog posts
Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.