Creating the Web Server
Learn to create a basic Deno web server.
We'll cover the following...
Steps to create a server
Now that our functionality is in place, we need to expose it via a web server. Let’s use what we’ve learned from the standard library to create it by following these steps:
- Create a file named
index.ts
inside thesrc/web
folder, and add the logic to create a server.
Press + to interact
import { serve } from "https://deno.land/std@0.83.0/http/server.ts";const PORT = 8080;const server = serve({ port: PORT });console.log(`Server running at https://localhost:${PORT}`);for await (let req of server) {req.respond({ body: 'museums api', status: 200 })}
Since we want our application to be easily configurable, we don’t want the port to be hardcoded here but to be configurable from the outside. We need to export this server creation logic as a function.
- Wrap the server logic creation inside a function that receives the configuration and
port
as an argument:
Press + to interact
import { serve } from "https://deno.land/std@0.83.0/http/server.ts";export async function createServer({configuration: {port}}) {const server = serve({ port });console.log(`Server running at http://localhost:${port}`);for await (let req of server) {req.respond({ body: "museums api", status: 200 })}}
We’ll notice that the TypeScript compiler will warn us that we shouldn’t use the port
defining its type.
- Make this function’s parameters an interface. This will help us in terms of documentation and will also add type safety and static checks:
Press + to interact
interface CreateServerDependencies {configuration: {port: number}}export async function createServer({configuration: {port}}: CreateServerDependencies) {...
Now that we have configured the web server, we can think of using it for our use case.
- Go back to
src/index.ts
, importcreateServer
, and use it to create a server running on port8080
:
Press + to interact
import { createServer } from "./web/index.ts";...createServer({configuration: {port: 8080}})...
5. Run it and see if it works:
deno run --allow-net src/index.ts
run the index.ts file
Here, we can see that we have a log stating that the server is running:
Press + to interact
Now, we can test ...