How to Create HTTP Server in Deno: Simple Guide
In Deno, you create an HTTP server using the
serve function from the std/http/server.ts module. You write an async function to handle requests and pass it to serve, which listens on a port and responds to incoming HTTP requests.Syntax
To create an HTTP server in Deno, import serve from std/http/server.ts. Then call serve with an async function that receives a Request object and returns a Response object. Optionally, specify the port to listen on.
- import: brings in the
servefunction - serve(): starts the server and listens for requests
- async handler: processes each request and returns a response
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve(async (req) => { return new Response("Hello from Deno HTTP server!", { status: 200, headers: { "content-type": "text/plain" }, }); }, { port: 8000 });
Example
This example creates a simple HTTP server that listens on port 8000 and responds with a plain text greeting to every request.
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; console.log("HTTP server is running on http://localhost:8000/"); serve(async (req) => { return new Response("Hello from Deno HTTP server!", { status: 200, headers: { "content-type": "text/plain" }, }); }, { port: 8000 });
Output
HTTP server is running on http://localhost:8000/
Common Pitfalls
Common mistakes when creating an HTTP server in Deno include:
- Not importing
servefrom the correct URL or version. - Forgetting to make the handler function
asyncwhen using asynchronous code. - Not returning a proper
Responseobject. - Not specifying the port or using a port already in use.
- Running the server without the necessary permissions (use
--allow-netflag).
Always run your server with deno run --allow-net your_file.ts to allow network access.
typescript
/* Wrong: Missing async and improper response */ import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve((req) => { // This will cause an error because the handler is not async and no Response returned console.log(req.url); }); /* Right: Async handler returning Response */ serve(async (req) => { return new Response("OK", { status: 200 }); }, { port: 8000 });
Quick Reference
Summary tips for creating HTTP servers in Deno:
- Import
servefromstd/http/server.tswith a fixed version. - Use an
asyncfunction to handle requests. - Return a
Responseobject with status and headers. - Run with
--allow-netpermission. - Specify the port in
serveoptions.
Key Takeaways
Use the built-in serve function from Deno's standard library to create HTTP servers.
Always write an async handler function that returns a Response object.
Run your Deno server with --allow-net permission to enable network access.
Specify the port explicitly to avoid conflicts and clarify where the server listens.
Import serve from a fixed version URL to ensure stable and consistent behavior.