Hello World
As a first introduction to Deno Deploy, let's deploy a little hello world
script. This will just respond to all incoming HTTP requests with Hello World
and a 200 OK
HTTP status. We will be using the Deno Deploy playground to
deploy and edit this script.
Before we start writing the actual script, let's go over some basics: Deno
Deploy lets you listen for incoming HTTP requests using the same
server side HTTP API as the Deno CLI. This API is rather low
level though, so instead of using this API directly we'll use the high level
HTTP API exposed by std/http
.
This API revolves around the serve
function that is exported from
https://deno.land/std@0.140.0/http/server.ts.
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
serve((_req) => {/* .. */});
Note: the port number we listen on is not important, as Deno Deploy will automatically route requests from the outside world to whatever port we listen on.
The handler function is called with two arguments: a Request
object, and a ConnInfo
object. The Request
object contains the
request data, and the ConnInfo
object contains information about the
underlying connection, such as the origin IP address. You must return a
Response
object from the handler function.
Let's use this information to finish our hello world script:
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
serve((_req) => {
return new Response("Hello World!", {
headers: { "content-type": "text/plain" },
});
});
Let's now deploy this script using a Deno Deploy playground. To get started, create a new playground project by visiting https://dash.deno.com, signing in, and pressing the New Playground button.
You can now copy the above code into the editor on the left side of the screen. To save and deploy the script, press the Save & Deploy button on the right side of the top toolbar (or press Ctrl+S).
You can preview the result on the right side of the playground editor, in the
preview pane. You will see that if you change the script (for example
Hello, World!
-> Hello, Galaxy!
) and then re-deploy, the preview will
automatically update. The URL shown at the top of the preview pane can be used
to visit the deployed page from anywhere.
Even in the playground editor, scripts are deployed worldwide across our entire global network. This guarantees fast and reliable performance, no matter the location of your users.
Congratulations. You have now deployed your first script to Deno Deploy 👏!