0
0
DenoDebug / FixBeginner · 3 min read

How to Handle Requests in Deno Server: Simple Guide

In Deno, you handle requests by creating an HTTP server using serve from the standard library and defining a function that receives a Request object. You respond by returning a Response object inside that function, which the server sends back to the client.
🔍

Why This Happens

When you try to handle requests in Deno but don't return a proper Response object, the server will fail or not respond correctly. This often happens if you forget to return the response or return something else like undefined.

typescript
import { serve } from "https://deno.land/std@0.177.0/http/server.ts";

serve((req) => {
  console.log("Request received");
  // Missing return statement
});
Output
Error: The handler function must return a Response object or a Promise<Response>.
🔧

The Fix

You must return a Response object from the handler function. This tells Deno what to send back to the client. You can create a simple text response using new Response("Your message").

typescript
import { serve } from "https://deno.land/std@0.177.0/http/server.ts";

serve((req) => {
  console.log("Request received");
  return new Response("Hello from Deno server!", {
    status: 200,
    headers: { "content-type": "text/plain" },
  });
});
Output
When you visit the server URL, the browser shows: Hello from Deno server!
🛡️

Prevention

Always return a Response object from your request handler to avoid errors. Use async functions if you need to wait for data before responding. Test your server by visiting the URL or using tools like curl. Use Deno's built-in linting (deno lint) to catch missing returns early.

⚠️

Related Errors

Common related errors include:

  • TypeError: Returning a non-Response object causes this error.
  • Unhandled Promise: Forgetting to await async operations before returning.
  • 404 Not Found: Happens if you don't handle the request path properly.

Fix these by ensuring you return a proper Response, await async calls, and check request URLs.

Key Takeaways

Always return a Response object from your Deno server request handler.
Use async/await if your response depends on asynchronous operations.
Test your server responses with a browser or curl to confirm behavior.
Run deno lint to catch common mistakes like missing return statements.
Check request URLs if you want to handle different paths or methods.