Deno is a JavaScript runtime built on V8, the same JavaScript engine that powers Google Chrome. The original creator of Node.js created Deno to address some of the shortcomings and security concerns of Node.js.
Although it is relatively new, Deno has gained popularity as a secure and modern JavaScript runtime. Its focus on security, support for modern language features, and developer-friendly tools make it an appealing choice. You can use it to build server-side applications, command-line tools, and other JavaScript/TypeScript projects, like a simple API.
Installing Deno
Before you’re able to use Deno you have to download and install it. Deno’s installation varies depending on your operating system.
On macOS and Linux, you’re able to install Deno by running this command:
On Windows, you may install Deno with Powershell, using this command:
You can confirm that your installation was successful by running the command below:
The command above should print the Deno version to the console.
If you use VS Code as an IDE, you can downloadDeno’s VS Code extensionto add IntelliSense, enhancing your productivity and development experience when working with Deno projects.
After successfully installing the extension, create a.vscodefolder in your project’s root directory and create asettings.jsonfile in it.
Next, add the code block below to thesettings.jsonfile to enable IntelliSense:
Connecting to a Database
For this tutorial, you will use MongoDB as a database to persist data from your API.
To connect your Deno app to a MongoDB database, create adb.jsfile in your project root directory and add the code block below to it:
Unlike Node.js, which depends onpackage managerslike the Node Package Manager (npm) or yarn, Deno has a built-in package management system for importing and managing dependencies directly from URLs.
For example, the code block above importsMongoClientfrom the URLhttps://deno.land/x/mongo@v0.30.1/mod.ts, which leads to the package.
Then, using the imported Deno MongoDB driver (MongoClient), Deno establishes a connection between your application and a local MongoDB database.
In live scenarios, it is more secure to store your database credentials in an.envfile instead of storing them in plain text, as done above.
Creating a Database Model
While it is possible tointeract with a MongoDB databasewithout a database model, doing so can lead to unstructured and less maintainable code.
To avoid this, create aTodoModel.tsfile in your project’s root directory and structure your data by adding the code block below to the file:
The code block above defines an interfaceTodothat represents the structure of a single todo item. Then using the Todo interface, it creates a Todo collection by calling the collection method exposed by your previously created MongoDB instance.
Creating a Server With Oak
Oak is a middleware for Deno’s native HTTP server. It was inspired by Koa, which is analternative to Express.js.
To create a server with Oak, create amain.tsfile in your project root directory and add the code block below to your file.
The code block above importsApplicationfrom the Oak URL and creates an application instance (app) that listens for incoming traffic on port 8000.
Theapp.use(router.routes())line registers the router’s routes as middleware in the Oak application. This means that the application will match the registered routes will against incoming requests, and the corresponding handlers will run if a match exists.
Theapp.use(router.allowedMethods())line handles HTTP methods that are not explicitly defined in the router. For example, if it receives a request with an unsupported method, for example, an unregistered PUT request, theallowedMethods()middleware will automatically send an appropriate response (e.g.,405 Method Not Allowed).
Implementing CRUD Functionality
This tutorial will feature a simple todo API with CRUD functionality.
Create arouter.tsfile in your project’s root directory and add the code block below to your file:
The code block above imports and creates an instance of the Oak router. Using this instance, you may create route handlers for various HTTP methods by calling the respective method names (get,post,put,delete).
For example, the code block below is an example of how you can create a GET route handler that returns all the documents in your Todo collection.
To send a response object using Deno, you must assign theresponse.bodyobject on the RouterContex to the response object. The same applies to status codes.
To add other route handlers, you can chain them to the previous route handler.
The code block above defines a GET route handler that returns a single Todo item that matches the id in the URL params.
Next, define a CREATE route handler that adds new documents to your collection:
Next, add a PUT route handler that updates a Todo based on theidparameter, with the data sent in the request body.
Finally, create a DELETE route handler that removes a Todo from your MongoDB collection:
You can start your Deno app with this command:
By default, a Deno script cannot access anything outside its scope, such as the network or the file system. So to start your application, you must include various flags to grant Deno the required permissions.
–allow-netallows Deno to make network requests.–allow-readallows Deno to access the file system and read files.–allow-envallows Deno to access environmental variables. The–watchflag starts your Deno app in watch mode.
Migrating From Node.js to Deno
Migrating from Node.js to Deno for building REST APIs can bring significant security, developer productivity, and dependency management benefits. Using Deno’s secure runtime, native TypeScript support, and simplified dependency management, you’re able to easily create robust and efficient REST APIs.
However, Deno’s immature ecosystem may cause you to reconsider. If you do choose to migrate, weigh the pros and cons carefully.
Q: Should I Use Node or Deno?
It depends! These frameworks compete on similar footing, butNode and Deno differ in syntax and package management. Learn their strengths and pick whichever suits you best.
Q: How Can I Test the API I’ve Created?
Postman is an excellent toolyou can use to test any API. OtherAPI testing toolsare available.
Q: Are There Any Other JavaScript Runtimes Besides Node and Deno?
Node is certainly the most popular, and Deno is a great second choice. However,bun.js is also worth checking outfor its focus on speed.