Skip to main content

HTTP Server

Handling HTTP requests, serving responses, and managing server behavior.

Eg Deno.serveHttp, Deno.serve

Functions

f
Deno.serve

Serves HTTP requests with the given handler.

    Interfaces

    I
    Deno.HttpServer

    An instance of the server created using Deno.serve() API.

    I
    Deno.ServeDefaultExport

    Interface that module run with deno serve subcommand must conform to.

    I
    Deno.ServeHandlerInfo

    Additional information for an HTTP request and its connection.

    I
    Deno.ServeInit
    No documentation available
    I
    Deno.ServeOptions

    Options which can be set when calling Deno.serve.

    I
    Deno.ServeTcpOptions

    Options that can be passed to Deno.serve to create a server listening on a TCP port.

    I
    Deno.ServeUnixOptions

    Options that can be passed to Deno.serve to create a server listening on a Unix domain socket.

    I
    Deno.ServeVsockOptions

    Options that can be passed to Deno.serve to create a server listening on a VSOCK socket.

    Type Aliases

    T
    Deno.ServeHandler

    A handler for HTTP requests. Consumes a request and returns a response.


      function Deno.serve

      unstable

      Overload 1

      #serve(handler: ServeHandler<Deno.NetAddr>): HttpServer<Deno.NetAddr>

      Serves HTTP requests with the given handler.

      The below example serves with the port 8000 on hostname "127.0.0.1".

      Deno.serve((_req) => new Response("Hello, world"));
      

      Parameters #

      Return Type #

      Overload 2

      #serve(): HttpServer<Deno.UnixAddr>

      Serves HTTP requests with the given option bag and handler.

      You can specify the socket path with path option.

      Deno.serve(
        { path: "path/to/socket" },
        (_req) => new Response("Hello, world")
      );
      

      You can stop the server with an AbortSignal. The abort signal needs to be passed as the signal option in the options bag. The server aborts when the abort signal is aborted. To wait for the server to close, await the promise returned from the Deno.serve API.

      const ac = new AbortController();
      
      const server = Deno.serve(
         { signal: ac.signal, path: "path/to/socket" },
         (_req) => new Response("Hello, world")
      );
      server.finished.then(() => console.log("Server closed"));
      
      console.log("Closing server...");
      ac.abort();
      

      By default Deno.serve prints the message Listening on path/to/socket on listening. If you like to change this behavior, you can specify a custom onListen callback.

      Deno.serve({
        onListen({ path }) {
          console.log(`Server started at ${path}`);
          // ... more info specific to your server ..
        },
        path: "path/to/socket",
      }, (_req) => new Response("Hello, world"));
      

      Parameters #

      Return Type #

      Overload 3

      #serve(): HttpServer<Deno.VsockAddr>

      Serves HTTP requests with the given option bag and handler.

      Parameters #

      Return Type #

      Overload 4

      #serve(): HttpServer<Deno.NetAddr>

      Serves HTTP requests with the given option bag and handler.

      You can specify an object with a port and hostname option, which is the address to listen on. The default is port 8000 on hostname "0.0.0.0".

      You can change the address to listen on using the hostname and port options. The below example serves on port 3000 and hostname "127.0.0.1".

      Deno.serve(
        { port: 3000, hostname: "127.0.0.1" },
        (_req) => new Response("Hello, world")
      );
      

      You can stop the server with an AbortSignal. The abort signal needs to be passed as the signal option in the options bag. The server aborts when the abort signal is aborted. To wait for the server to close, await the promise returned from the Deno.serve API.

      const ac = new AbortController();
      
      const server = Deno.serve(
         { signal: ac.signal },
         (_req) => new Response("Hello, world")
      );
      server.finished.then(() => console.log("Server closed"));
      
      console.log("Closing server...");
      ac.abort();
      

      By default Deno.serve prints the message Listening on http://<hostname>:<port>/ on listening. If you like to change this behavior, you can specify a custom onListen callback.

      Deno.serve({
        onListen({ port, hostname }) {
          console.log(`Server started at http://${hostname}:${port}`);
          // ... more info specific to your server ..
        },
      }, (_req) => new Response("Hello, world"));
      

      To enable TLS you must specify the key and cert options.

      const cert = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n";
      const key = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n";
      Deno.serve({ cert, key }, (_req) => new Response("Hello, world"));
      

      Parameters #

      Return Type #

      Overload 5

      #serve(options: ServeUnixOptions & ServeInit<Deno.UnixAddr>): HttpServer<Deno.UnixAddr>

      Serves HTTP requests with the given option bag.

      You can specify an object with the path option, which is the unix domain socket to listen on.

      const ac = new AbortController();
      
      const server = Deno.serve({
        path: "path/to/socket",
        handler: (_req) => new Response("Hello, world"),
        signal: ac.signal,
        onListen({ path }) {
          console.log(`Server started at ${path}`);
        },
      });
      server.finished.then(() => console.log("Server closed"));
      
      console.log("Closing server...");
      ac.abort();
      

      Parameters #

      Return Type #

      Overload 6

      #serve(options: ServeVsockOptions & ServeInit<Deno.VsockAddr>): HttpServer<Deno.VsockAddr>

      Serves HTTP requests with the given option bag.

      The VSOCK address family facilitates communication between virtual machines and the host they are running on: https://man7.org/linux/man-pages/man7/vsock.7.html

      Parameters #

      Return Type #

      Overload 7

      #serve(options: (ServeTcpOptions | (ServeTcpOptions & TlsCertifiedKeyPem)) & ServeInit<Deno.NetAddr>): HttpServer<Deno.NetAddr>

      Serves HTTP requests with the given option bag.

      You can specify an object with a port and hostname option, which is the address to listen on. The default is port 8000 on hostname "0.0.0.0".

      const ac = new AbortController();
      
      const server = Deno.serve({
        port: 3000,
        hostname: "127.0.0.1",
        handler: (_req) => new Response("Hello, world"),
        signal: ac.signal,
        onListen({ port, hostname }) {
          console.log(`Server started at http://${hostname}:${port}`);
        },
      });
      server.finished.then(() => console.log("Server closed"));
      
      console.log("Closing server...");
      ac.abort();
      

      Parameters #

      Return Type #


      interface Deno.HttpServer

      extends AsyncDisposable

      An instance of the server created using Deno.serve() API.

      Type Parameters #

      #Addr extends Deno.Addr = Deno.Addr

      Properties #

      #finished: Promise<void>

      A promise that resolves once server finishes - eg. when aborted using the signal passed to ServeOptions.signal.

      The local address this server is listening on.

      Methods #

      #ref(): void

      Make the server block the event loop from finishing.

      Note: the server blocks the event loop from finishing by default. This method is only meaningful after .unref() is called.

      #unref(): void

      Make the server not block the event loop from finishing.

      #shutdown(): Promise<void>

      Gracefully close the server. No more new connections will be accepted, while pending requests will be allowed to finish.


      interface Deno.ServeDefaultExport

      Interface that module run with deno serve subcommand must conform to.

      To ensure your code is type-checked properly, make sure to add satisfies Deno.ServeDefaultExport to the export default { ... } like so:

      export default {
        fetch(req) {
          return new Response("Hello world");
        }
      } satisfies Deno.ServeDefaultExport;
      

      Properties #

      A handler for HTTP requests. Consumes a request and returns a response.

      If a handler throws, the server calling the handler will assume the impact of the error is isolated to the individual request. It will catch the error and if necessary will close the underlying connection.

      #onListen: (localAddr: Deno.Addr) => void
      optional

      The callback which is called when the server starts listening.




      interface Deno.ServeOptions

      Options which can be set when calling Deno.serve.

      Type Parameters #

      #Addr extends Deno.Addr = Deno.Addr

      Properties #

      #signal: AbortSignal
      optional

      An AbortSignal to close the server and all connections.

      #onError: (error: unknown) => Response | Promise<Response>
      optional

      The handler to invoke when route handlers throw an error.

      #onListen: (localAddr: Addr) => void
      optional

      The callback which is called when the server starts listening.


      interface Deno.ServeTcpOptions

      Options that can be passed to Deno.serve to create a server listening on a TCP port.

      Properties #

      #transport: "tcp"
      optional

      The transport to use.

      #port: number = 8000
      optional

      The port to listen on.

      Set to 0 to listen on any available port.

      #hostname: string = "0.0.0.0"
      optional

      A literal IP address or host name that can be resolved to an IP address.

      Note about 0.0.0.0 While listening 0.0.0.0 works on all platforms, the browsers on Windows don't work with the address 0.0.0.0. You should show the message like server running on localhost:8080 instead of server running on 0.0.0.0:8080 if your program supports Windows.

      #reusePort: boolean
      optional

      Sets SO_REUSEPORT on POSIX systems.

      #tcpBacklog: number = 511
      optional

      Maximum number of pending connections in the listen queue.

      This parameter controls how many incoming connections can be queued by the operating system while waiting for the application to accept them. If more connections arrive when the queue is full, they will be refused.

      The kernel may adjust this value (e.g., rounding up to the next power of 2 plus 1). Different operating systems have different maximum limits.




      type alias Deno.ServeHandler

      A handler for HTTP requests. Consumes a request and returns a response.

      If a handler throws, the server calling the handler will assume the impact of the error is isolated to the individual request. It will catch the error and if necessary will close the underlying connection.

      Type Parameters #

      #Addr extends Deno.Addr = Deno.Addr

      Definition #

      (
      request: Request,
      ) => Response | Promise<Response>

      Did you find what you needed?

      Privacy policy