How to Use Request and Response in Deno: Simple Guide
In Deno, you handle HTTP
Request and Response objects inside an async function that receives a Request and returns a Response. Use the fetch event or serve from the standard library to listen for requests and send back responses.Syntax
In Deno, a typical HTTP handler is an async function that takes a Request object and returns a Response object. The Request contains details about the incoming HTTP request, and the Response defines what you send back to the client.
- Request: Holds method, headers, URL, and body.
- Response: Contains status code, headers, and body to send.
typescript
async function handler(req: Request): Promise<Response> { // process req return new Response("Hello from Deno", { status: 200 }); }
Example
This example shows a simple HTTP server using Deno's serve function. It listens on port 8000, reads the request method and URL, and sends back a plain text response.
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve(async (req: Request) => { const url = new URL(req.url); if (req.method === "GET" && url.pathname === "/") { return new Response("Welcome to Deno server!", { status: 200, headers: { "content-type": "text/plain" }, }); } else { return new Response("Not Found", { status: 404 }); } }, { port: 8000 });
Output
Server running on http://localhost:8000
When you visit http://localhost:8000/ you see: Welcome to Deno server!
Common Pitfalls
Some common mistakes when using Request and Response in Deno:
- Not returning a
Responseobject from the handler function causes the server to hang or error. - Forgetting to set the correct
Content-Typeheader can make the client misinterpret the response. - Trying to read the request body multiple times without cloning it will fail because the body stream can be read only once.
typescript
/* Wrong: Missing Response return */ serve(async (req) => { console.log(req.method); // No return here causes error }); /* Right: Always return a Response */ serve(async (req) => { return new Response("OK", { status: 200 }); });
Quick Reference
Here is a quick summary of key points when working with Request and Response in Deno:
- Request: Use
req.method,req.url,req.headers, andawait req.text()orawait req.json()to read body. - Response: Create with
new Response(body, { status, headers }). - Use
servefromstd/http/server.tsto start a server easily. - Always return a
Responsefrom your handler.
Key Takeaways
Handle HTTP requests in Deno by writing an async function that takes a Request and returns a Response.
Use the standard library's serve function to listen for requests and send responses easily.
Always return a Response object with proper status and headers to avoid server errors.
Read request body only once and set correct Content-Type headers in responses.
Use URL and method from Request to route and handle different endpoints.