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
portto 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
Responseobject 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 globalDeno.servein Deno 1.28+. - Handler: Function receives
Request, returnsResponse. - Options: Pass
{ port: number }to set server port. - Run: Await
serveto 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.