Deploy a (Node.js + Express + MongoDB) API to Azure App Service via Visual Studio Code

bjhaid_93

/[Abejide Femi Jr]\s/

Posted on January 15, 2021

Deploy a (Node.js + Express + MongoDB) API to Azure App Service via Visual Studio Code

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
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

Click on create Azure Cosmos DB account

Alt Text

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

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

Alt Text

You can leave the backup with the default config
Alt Text

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

Alt Text

If validation is successful, select the create button

Alt Text

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

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
Enter fullscreen mode Exit fullscreen mode

In the terminal

In the package.json file, we need to set a start script

"start": "node index.js
Enter fullscreen mode Exit fullscreen mode

Create an index.js file where we will set up express to listen to connection on port 4000 locally.

const express = require("express");

const app = express();

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

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

Enter fullscreen mode Exit fullscreen mode

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.

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;

Enter fullscreen mode Exit fullscreen mode

We need to create a model, we will have just one model, that is the Post model with two fields(title and description).

const mongoose = require("mongoose");

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

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

module.exports = Post;

Enter fullscreen mode Exit fullscreen mode

I created some dummy data that we can seed into the database and retrieve it in the controller.

[
  {
    "_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!"
  }
]
Enter fullscreen mode Exit fullscreen mode

The seed file inserts the data into the Post model, and we have a console.log to confirm the data was seeded.

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();

Enter fullscreen mode Exit fullscreen mode

Let’s create the controller, with one endpoint, to get all post.

const Post = require("../model/Post");

exports.getAllPosts = async (req, res) => {
  const posts = await Post.find()
  res.status(200).json(posts)
};
Enter fullscreen mode Exit fullscreen mode

And the post router file

const express = require('express')
const { getAllPosts } = require('../controller/post')

const router = express.Router()

router.get('/', getAllPosts)

module.exports = router
Enter fullscreen mode Exit fullscreen mode

Then we mount the route in the index.js file and also require the database config.

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}`);
});

Enter fullscreen mode Exit fullscreen mode

Let’s seed the data into the database by running

node seed.js
Enter fullscreen mode Exit fullscreen mode

from the console, we can confirm that the data is seeded

Alt Text

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

Alt Text

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

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
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
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
We can now deploy via VSCode, by first selecting the Azure icon, the up arrow button in App Service
Alt Text
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
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

Once the deployment is complete, click on the Browse website.
Alt Text
Now we can visit the endpoint from the hosted URL https://node-azure-tuts.azurewebsites.net/api/v1/posts.
Alt Text
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

💖 💪 🙅 🚩
bjhaid_93
/[Abejide Femi Jr]\s/

Posted on January 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related