Deploy a (Node.js + Express + MongoDB) API to Azure App Service via Visual Studio Code
Tags: azure, node, javascript
Published: 2021-01-15 21:34:13

---
title: Deploy a (Node.js + Express + MongoDB) API to Azure App Service via Visual Studio Code
published: true
description: 
tags: azure,node,javascript
---
In this tutorial, we will implement an API with Node.js and Express then deploy it to Azure App Service using Azure Cosmos DB for MongoDB API as the database.

**Prerequisite**
Node.js
Visual Studio Code
Azure account

According to Microsoft Azure **The Azure free account includes access to a number of Azure products that are free for 12 months, $200 credit to spend for the first 30 days of sign up, and access to more than 25 products that are always free**. Azure App Service and Azure Cosmos Database are part of the free service, you can check for the other services here https://azure.microsoft.com/en-us/free/free-account-faq/.

To create an account on Azure, you can simply do that by visiting this link https://azure.microsoft.com/en-gb/, and selecting Try Azure for free. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/drowt190ewh9oitgufvs.png)
After doing that, we need to set up a database for the application by creating the Azure Cosmos Database for MongoDB API. Search for Azure Cosmos DB in the search bar, and select Azure Cosmos DB under services 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3xs0ni5gylbq77tz9zn4.png)

Click on create Azure Cosmos DB account

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yw0i5knc6q336enpik5n.png)

On the create page, you need to create a resource group if you don’t have one,  you can provide any name you want for the account name, for the API you need to select Azure Cosmos DB for MongoDB API because we will be using MongoDB, you can also select your desired location. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tgqv4qtlea05sgx6ob62.png)

The next configuration is the Networking, select All networks, in a real-world application, Private endpoint will be ideal.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/28hfk59edphh2d5m0q7n.png)

You can leave the backup with the default config 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/d4tg78sf9qlkhdp8b2tz.png)

Also, you can use the Encryption default config You can set a tag with a key of env and value of dev.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zvjyqojqgx43lx4813ax.png)

If validation is successful, select the create button 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/plvmtkr982vrzwmx1y0b.png)

It takes about 2-5mins for this process to be complete. Once this is done, select **Node.js** as the platform, and copy the connection string that is provided on the page, we will be using it in our application. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jvz0mk97m7egedi3kblk.png)

Now let's build the API endpoint and use this database that we just created

First, create a project, and run 
```
npm init -y
npm i express mongoose dotenv
```
In the terminal

In the package.json file, we need to set a start script
```
"start": "node index.js
```
Create an index.js file where we will set up express to listen to connection on port 4000 locally.
```js
const express = require("express");

const app = express();

const port = process.env.PORT || 4000;

app.listen(port, () => {
  console.log(`listening on ${port}`);
});

```

Create a config.js file, that is where we will implement the database configuration, note that we also need to create a .env file and set the **DB_PASSWORD**  so we don’t expose the database credentials to the public.
```js
const mongoose = require("mongoose");
const dotenv = require("dotenv");

dotenv.config();
const { DB_PASSWORD } = process.env;

const connectDB = () => {
  return mongoose
    .connect(
      `mongodb://node-rest-api:${DB_PASSWORD}@node-rest-api.mongo.cosmos.azure.com:10255/?ssl=true&appName=@node-rest-api@&retryWrites=false`,
      {
        useCreateIndex: true,
        useNewUrlParser: true,
        useFindAndModify: true,
        useUnifiedTopology: true,
      }
    )
    .then(() => console.log(`database connected successfully`))
    .catch((err) => console.log(err.message));
};

module.exports = connectDB;

```
We need to create a model, we will have just one model, that is the Post model with two fields(title and description). 
```js
const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
  title: {
    type: String,
  },
  description: {
    type: String,
  },
});

const Post = mongoose.model("Post", postSchema);

module.exports = Post;

```
I created some dummy data that we can seed into the database and retrieve it in the controller.
```js
[
  {
    "_id": "5c8a34ed14eb5c17645c9108",
    "title": "cash app",
    "description": "Cras mollis nisi parturient mi nec aliquet suspendisse sagittis eros condimentum scelerisque taciti mattis praesent feugiat eu nascetur a tincidunt"
  },
  {
    "_id": "5c8a355b14eb5c17645c9109",
    "title": "kor po ke",
    "description": "Tempus curabitur faucibus auctor bibendum duis gravida tincidunt litora himenaeos facilisis vivamus vehicula potenti semper fusce suspendisse sagittis!"
  }
]
```

The seed file inserts the data into the Post model, and we have a console.log to confirm the data was seeded.
```js
const Post = require("./model/Post");
const postData = require("./data/post.json");

require("./config")();

const seedData = async () => {
  try {
    await Post.insertMany(postData);
    console.log("data seeded");
  } catch (err) {
    console.log(err.message);
  }
};
seedData();

```
Let’s create the controller, with one endpoint, to get all post.
```js
const Post = require("../model/Post");

exports.getAllPosts = async (req, res) => {
  const posts = await Post.find()
  res.status(200).json(posts)
};
```
And the post router file 
```js
const express = require('express')
const { getAllPosts } = require('../controller/post')

const router = express.Router()

router.get('/', getAllPosts)

module.exports = router
```

Then we mount the route in the index.js file and also require the database config.
```js
const express = require("express");
const postRoute = require("./route/post");

require("./config")();

const app = express();

app.use("/api/v1/posts", postRoute);

const port = process.env.PORT || 4000;

app.listen(port, () => {
  console.log(`listening on ${port}`);
});

```

Let’s seed the data into the database by running 
```
node seed.js
```
from the console, we can confirm that the data is seeded 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p54bx17969038lftfce6.png)

You can also see the post document under test, in the Azure portal, when you click on Data Explorer 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hhxm8ijjr4f2kkaqqcrb.png)

Before we finally deploy the app, you need to install this extension https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack  in your VSCode. 

After installation the Azure menu will appear in VSCode, you will be prompted to sign in with your Azure account. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1rti44bg0375kzp9hpdk.png)

Let’s go back to the Azure portal to create the App Service. Select create App Service 

Provide the name of the web app, name of the resource group, the runtime stack(I used Node 12 LTS) 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lbe09igcivlsbmihxznq.png)
Next is Monitoring, we need to enable monitoring, it provides detailed observability in our application We can leave the tags empty, and click on create.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pihwg81i8xi1uclk0j7t.png)
This process takes about 2-5mins, once this is done, we need to set the environment variable that we used in the application by clicking on the New application setting and providing the key and the value, then click on save. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/f3ctijempk5rwtzq0y5x.png)
We can now deploy via VSCode, by first selecting the Azure icon, the up arrow button in App Service 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mnsea66uog56tzgtokle.png)
Select the current project, if you can’t see the App Service that we just created, reload VsCode by running Ctrl+Shift+P and select reload window. Select the App Service once it appears 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3889nvk27fts8l4u4gj5.png)
You will be asked if you want to always deploy to the App Service while the deployment is in progress, you can select yes. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ljjdhm30912nvvcbjmxh.png)

Once the deployment is complete, click on the Browse website.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vey9czlo5hw2c4ydoij5.png)
Now we can visit the endpoint from the hosted URL https://node-azure-tuts.azurewebsites.net/api/v1/posts.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/onau92vwng6mzjrbrgxm.png)
Link to  the GitHub repo - https://github.com/abejide001/node-azure-appservice

**Conclusion**
In this tutorial we deployed a REST API to Azure App Service, using Azure Cosmos DB as the database. You can delete these resources that were created in the Azure Portal if you won’t use them any longer.
You might also want to consider using Terraform or Azure Resource Manager to setup Azure Cosmos DB and Azure App Service rather than doing it manually