0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Deno.serve for Simple HTTP Servers

Use Deno.serve to quickly create an HTTP server by passing a handler function that receives requests and returns responses. It runs the server on a specified port and handles requests asynchronously with minimal setup.
๐Ÿ“

Syntax

The basic syntax of Deno.serve involves calling it with a handler function that takes a Request object and returns a Response or a promise resolving to one. You can also pass an options object to specify the port and other settings.

  • handler: A function that processes incoming requests.
  • options: Optional settings like port to define the listening port.
typescript
Deno.serve(handler: (req: Request) => Response | Promise<Response>, options?: { port?: number }): Promise<void>
๐Ÿ’ป

Example

This example shows a simple HTTP server that responds with "Hello from Deno!" to every request on port 8000. It demonstrates how to use Deno.serve with an async handler function.

typescript
await Deno.serve(async (req) => {
  return new Response("Hello from Deno!", {
    status: 200,
    headers: { "content-type": "text/plain" },
  });
}, { port: 8000 });
Output
Server listening on http://localhost:8000/
โš ๏ธ

Common Pitfalls

Common mistakes when using Deno.serve include:

  • Not returning a Response object from the handler, causing the server to hang.
  • Forgetting to await Deno.serve, which can cause the script to exit immediately.
  • Not specifying a port, which defaults to 8000 but might conflict with other services.

Always ensure your handler returns a valid Response and that you await the server start.

typescript
/* Wrong: Missing return of Response */
await Deno.serve((req) => {
  console.log("Request received");
});

/* Right: Return a Response */
await Deno.serve((req) => {
  return new Response("OK");
});
๐Ÿ“Š

Quick Reference

Here is a quick summary of Deno.serve usage:

  • Import: Use import { serve } from "https://deno.land/std/http/server.ts" or use the global Deno.serve in Deno 1.28+.
  • Handler: Function receives Request, returns Response.
  • Options: Pass { port: number } to set server port.
  • Run: Await serve to keep server running.
โœ…

Key Takeaways

Use Deno.serve with an async handler function that returns a Response to create HTTP servers easily.
Always await Deno.serve to keep the server running and handle requests.
Specify the port in options to avoid conflicts and control where the server listens.
Return a valid Response object from the handler to avoid hanging requests.
Deno.serve is built-in from Deno 1.28+, no extra dependencies needed.